Home  >  Java 7

Example of ForkJoinTask in Java

By Arvind Rai, December 26, 2013
java.util.concurrent.ForkJoinTask has been introduced in JDK 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.
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);
class DemoTask implements Callable<String>{
       public String call() {
              try {
              } catch (InterruptedException e) {
              return "Task Done";


complete() method completes a task and assigns the result in passed argument of this method. Mainly this method is used to receive the result of asynchronous task.


This method returns the ForkJoinPool within which the given ForkJoinTask is running.


By its names it is clear that it tries to un fork the task within a ForkJoinPool. A task which has been newly forked and yet has not been stated by any thread within the ForkJoinPool, can be un fork.


This method returns true if task is done by any way either normal termination, or any exception.

©2020 concretepage.com | Privacy Policy | Contact Us