Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 7: Fork/Join Framework

Can someone explain what Fork/Join is?

like image 853
Fork-Join Avatar asked Aug 19 '10 17:08

Fork-Join


People also ask

What is the fork join framework in Java?

The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

What is executor framework How is it different from fork join framework?

In short, the main difference between the Executor framework and ForkJoinPool is that the former provides a general-purpose thread pool, while the latter provides a special implementation that uses a work-stealing pattern for efficient processing of ForkJoinTask.

When we should use fork and join?

The fork/join framework was designed to speed up the execution of tasks that can be divided into other smaller subtasks, executing them in parallel and then combining their results to get a single one.


1 Answers

I will answer what is Fork Join parallelism. This is one of the parallel design pattern widely used in many systems to achieve concurrency. I will explain this design pattern using a example.

For example lets say we have program which executes sequence of tasks :

A -> B -> C -> D. Here A,B,C,D are tasks.

  • A takes 8 seconds
  • B takes 4 seconds
  • C takes 6 seconds
  • D takes 7 seconds

So it will take total of 8+4+6+7 = 25 seconds for this program execution.

Now you found out that tasks A,B,C are independent and D is depend on A,B,C tasks' results. Now you may get a feeling that instead of waiting for A to finish we can start the execution of B simultaneously. Same for Task C can start the task simultaneously with A and B. What you can do is: You can invoke 3 new threads by your main thread and assign them A,B,C tasks and wait for the results before start the execution of task D. If your machine has multiple cores then these threads can run in parallel.

Now the execution time taken for the program is :

max(time_taken_A,_B,_C) + time_taken_D + threading_overhead_time

which is almost equal to = 8 + 7 + k = 15 + k;

In fork join parallelism we can offload tasks with a new thread only if these tasks are independent. Other wise we will face race conditions. If you have a program where one task is waiting for another task execution but this is not dependent on its results then you can offload these two tasks with new threads using fork join parallelism and you can get performance boost. But always think about the threading over head. If your tasks are very light weighted then using these parallel patterns will decrease your performance because of the thread creation, context switching overheads.

like image 145
Tharsanan Avatar answered Sep 19 '22 11:09

Tharsanan