Friday, June 19, 2015

Concurrency Utilities Fork/Join Framework

Forks Join!

With the advent of multiple processors, the code also need to evolve. We need to write code which can spawn Threads in such a manner so as to take complete use of multiple processors. The idea is to use all available processing power which leads to enhanced performance. No Thread should remain free.

Fork/Join framework is an implementation of ExecutorService. We have a ThreadPool. Tasks are allotted to the worker threads. The difference here is if some thread is free, it will steal the work from a busy thread, thereby maximizing performance.
ForkJoinPool is the implementation of ExecutorService which can run ForkJoinTasks. It is different from other ExecutorServices as the threads in the pool tries to steal the subtasks created by other Tasks (being processed by other threads). It’s like a workaholic employee who ends up doing other people’s work also. In effect it improves firms overall performance.
1
2
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new SumArray(array, 0, array.length));
SumArray extends ForkJoinTask (RecursiveTask/RecursiveAction). See here the analogy with a simple ThreadPoolExecutor, which requires a Runnable/Callable task.
The SumArray needs to have function compute() (analogous to run()) which will be called post pool.invoke() (analogous to execute()). Also a function invokeAll() is available to the SumArray, which is just like invoke, but takes multiple ForkJoinTasks and assign them to the ForkJoinPool.
1
2
3
4
5
6
7
8
9
10
11
protected void compute() {
        if(length < 1000 ) { //No need to Split the Task
            sumDirectly();
            return;
        }
        //Need to split the Task
        invokeAll(new SumArray(array, 0, length/2),
                new SumArray(array, length/2, length));
}

No comments:

Post a Comment