Java Concurrency Models

Java concurrency models guarantees data consistency where multiple threads are used.

Now let us look at the different types of models:

Parallel Workers:

Here, a delegator delegates the jobs to different workers. For example, there are 3 flats which require maintainance and furnishing. So the delegator delegates those 3 jobs to 3 workers and they work in parallel improving the efficiency.

Similarly at the system level, delegator delegates jobs to multiple workers(you can say threads) and those workers execute in parallel in different cpu’s. So the performance here is efficient as the model makes efficient use of cpu’s.

But the problem arises when it is shared architecture. That is the workers which can be threads can share some data. So here comes problems such as race condition.So with proper use of synchronization, such problems can be avoided if it is a shared architecture.

Assembly Line:

This is one of the most efficient non blocking concurrency model.

It is similar to workers workign in factory. They do a task and forward the same to the next worker for further processing.

So for example in assembly line, the first worker reads a file then forwards the result to the next worker who does some processing on the file data and forwards it to next worker for further processing.

When the second worker was doing some processing, the first worker started reading next set of files. So here it is totally a non blocking I/O operation. Non-blocking IO means that when a worker starts an IO operation (e.g. reading a file or data from a network connection) the worker does not wait for the IO call to finish. Whatever data it has read it can forward to the next worker on the assembly line and then read the remaining file. By doing this, both the workers are non blocking.

Another benefit of assembly line model is that it is a non shared architecture. That is no data whether an object or a data structure is common or you can say shared between multiple workers.So concurrency problems like race conditions are avoided and there is no need to implement synchronization.

The only problem is that the code base is huge for this model since each worker has it’s own business logic. So code analysing may take time.

So to summarize, assembly line is kind of a reactive driven system.

Functional Parallelism:

The basic idea of functional parallelism is that you implement your program using function calls. Functions can be seen as actors that send messages to each other, just like in the assembly line concurrency model. When one function calls another, that is similar to sending a message.

With Java 7 we got the java.util.concurrent package contains the ForkAndJoinPool which can help you implement something similar to functional parallelism. With Java 8 we got parallel streams which can help you parallelize the iteration of large collections