214. Fork/join framework

We've already had an introduction to the fork/join framework in the Work-stealing thread pool section.

Mainly, the fork/join framework is meant to take a big task (typically, by big we understand a large volume of data) and recursively split (fork) it into smaller tasks (subtasks) that can be performed in parallel. In the end, after all the subtasks have been completed, their results are combined (joined) in a single result.

The following diagram is a visual representation of a fork-join flow:

In API terms, a fork/join can be created via java.util.concurrent.ForkJoinPool.

Before JDK 8, the recommended approach relied on a public static variable as follows:

public static ForkJoinPool forkJoinPool = new ForkJoinPool();

Starting with JDK 8, we can do it as follows:

ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();

Both approaches avoid the unpleasant situation of having too many pool threads on a single JVM, caused by the parallel operations that created their own pools.

For a custom ForkJoinPool, rely on the constructors of this class. JDK 9 has added the most comprehensive one so far (details are available in the documentation).

A ForkJoinPool object manipulates tasks. The base type of task executed in  ForkJoinPool is ForkJoinTask<V>. More precisely, the following tasks are executed:

  • RecursiveAction for the void tasks
  • RecursiveTask<V> for tasks that return a value
  • CountedCompleter<T> for tasks that need to remember the pending task count

All three types of tasks have an abstract method named compute() in which the task's logic is shaped.

Submitting tasks to ForkJoinPool can be accomplished via the following:

  • execute() and submit()
  • invoke() for forking the task and waiting for the result
  • invokeAll() for forking a bunch of tasks (for example, a collection)
  • fork() for arranging to asynchronously execute this task in the pool, and join() for returning the result of the computation when it is done

Let's start with a problem solved via RecursiveTask.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.29.119