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
else
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
     f1.fork();
     Fibonacci f2 = new Fibonacci(n - 2);
     return f2.compute() + f1.join();
   }
 }

For more details go through the Java doc and check this example too:
http://www.javaworld.com/javaworld/jw-10-2011/111004-jtip-recursion-in-java-7.html


Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s