Sunday 17 April 2016

Fork Join Framework

Fork Join technology was introduced with Java version 7, to be able to deal with parallel concurrency.

This technology is based in splitting a task recursively until it is small enough to be performed. The sub-tasks will be executed in parallel in different threads. When the sub-tasks have finished, then a join is invoked to merge the results into one.




























Example. The following example is very simple. It consists on a function that calculates consecutive natural numbers in an interval. The class will receive two parameters (number min. and max.). If this interval is greater than 6 (in the example) the task will be split into two sub-tasks.

The class extends RecursiveTask<Long> and implements method compute(). As our class is a task it will be invoked by ForkJoinPool



Output console:
Splitting task
Computing
Result1: 21
Computing
Result1: 57
Result2: 78