ForkJoinTask in Java
December 26, 2013
java.util.concurrent.ForkJoinTask has been introduced in Java 7 and is the part of fork join framework. ForkJoinTask is an entity that is like thread but with much lighter weight. ForkJoinTask runs within ForkJoinPool. With the help of small number of threads, ForkJoinPool can run large number of ForkJoinTask. ForkJoinTask is submitted to ForkJoinPool and then ForkJoinTask starts executing from its exec() method. ForkJoinTask can also start some sub task inside it. ForkJoinTask is a lightweight for of java.util.concurrent .Future . The basic task of ForkJoinTask is computational and two methods of ForkJoinTask is normally called that is fork and join. We will discuss these methods and some other methods and usages.
fork() and join() in ForkJoinTask
fork() method is used to execute a task within the ForkJoinPool. It executes task asynchronously. join() methods waits for task completion started by fork() method and returns the result once done. For the demo of fork and join method refer the link .ForkJoinTask .adapt
It returns a new ForkJoinTask that will be invoked using ForkJoinPool. adapt() method can run callable and runnable threads. We will see one demo here.ForkJoinTaskDemo.java
package com.concretepage.util.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; public class ForkJoinTaskDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ForkJoinPool fjp = new ForkJoinPool(); DemoTask task = new DemoTask(); ForkJoinTask<String> fjt = ForkJoinTask.adapt(task); fjp.invoke(fjt); System.out.println(fjt.isDone()); } } class DemoTask implements Callable<String>{ public String call() { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println(e); } return "Task Done"; } }