ForkJoinPool in Java 7

The new ForkJoinPool in Java 7 provides significant performance improvement for programs that involve recursion.

As mentioned in the Java website, the basic principle is:


if (my portion of the work is small enough)
  do the work directly
split my work into two pieces
invoke the two pieces and wait for the results


As a user following are your responsibilities:

  • Creation of a ForkJoinPool objec
  • Creation of main ForkJoinTask – it can be a RecursiveTask or RecursiveAction – and submit to the pool
    • Add logic inside the task to check if the current portion of work is small enough before executing it
    • Add logic inside the task to split the work (create tasks again) if the current potion of work is more

Thats it, no need to create any threads. Dont worry about synchroniztion etc.
A simple example is provided in the Java doc for ForkJoinPool class.

class Fibonacci extends RecursiveTask {
   final int n;  
   Fibonacci(int n) { this.n = n; }
   Integer compute() {
     if (n <= 1)                     // the check 
        return n;
     Fibonacci f1 = new Fibonacci(n - 1);     // sub-task creation
     Fibonacci f2 = new Fibonacci(n - 2);
     return f2.compute() + f1.join();

For more details go through the Java doc and check this example too:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s