May 16, 2014

Java 7 fork and join tutorial with a diagram and an example

Q. How does java.util.concurrent.RecursiveTask work?A. It uses a single ForkJoin pool to execute tasks in parallel for both computing sum of numbers recursively and chunking (or breaking) them into chunks of say 3 or less as per the following example.

Here is an example, where a an array of given numbers are summed in parallel by multiple threads. The batch size is 3. So, each thread processes 3 or less numbers asynchronously (i.e. fork) and the join to compute the final results.

Q. Where to use fork/join as opposed to using the ExecutorService framework?

The Fork/Join Framework in Java 7 is designed for work that can be broken down into smaller tasks and the results of those tasks combined to produce the final result. Multicore processors are now widespread across server, desktop, and laptop hardware. They are also making their way into smaller devices, such as smartphones and tablets. Fork/Join offers serious gains for solving problems that involve
recursion. Because recursion is fundamental to parallel programming on
multicore platforms. Java recursion tutorial example with a diagram and example.

The fork/join tasks should operate as “pure” in-memory algorithms in which no I/O operations come into play. Also, communication between tasks through shared state should be avoided as much as possible, because that implies that locking might have to be performed. Ideally, tasks communicate only when one task forks another or when one task joins another.

ExecutorService continues to be a fine solution for many concurrent programming tasks, and in programming scenarios in which recursion is vital to processing power, it makes sense to use Fork/join. This fork and join feature is used in Java 8 parallel stream processing with lambda expressions.