Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
thread pool

How to create a thread pool using the ForkJoinPool class in Java

Tarun Telang

Introduction

The java.util.concurrent.ForkJoinPool is used to execute ForkJoinTask. It also provides the entry point for the non-ForkJoinTask clients. A ForkJoinTask is a task that can be divided into smaller tasks, which can be executed concurrently.

Constructors of ForkJoinPool class

The constructor initializes the ForkJoinPool instance with the given parameters.

Syntax

The ForkJoinPool class provides three constructors:

public ForkJoinPool()

public ForkJoinPool(int parallelism)

public ForkJoinPool(int parallelism,
                    ForkJoinWorkerThreadFactory factory,
                    Thread.UncaughtExceptionHandler handler,
                    boolean asyncMode)
The syntax of the constructor of the `ForkJoinPool` class

Parameters:

  • parallelism: This parameter allows you to choose the desired parallelism level. If the value is less than or equal to zero, is passed to this parameter then the default value, which is equal to Runtime.availableProcessors() will be used. The Runtime.availableProcessors() method returns the number of processors available to the Java virtual machine. For example, if -1 (as it is less than or equal to zero) is passed and the number of processors is 4, then the ForkJoinPool will have a parallelism level of 4. On the other hand, if 2 (as it is greater than zero) is passed, the ForkJoinPool will have a parallelism level of 2 irrespective of the number of processors.
  • factory: The factory for creating new ForkJoinWorkerThreads, or null for the default.
  • handler: The UncaughtExceptionHandler to use when execution errors occur, or null to use the default.
  • asyncMode: If true, establishes a local first-in-first-out scheduling mode for forked tasks that are never joined. This mode may be more appropriate than default locally stack-based mode in applications in which worker threads only process event-style asynchronous tasks.

Methods of ForkJoinPool class

The ForkJoinPool class provides the following methods to work with fork join pools

Methods of ForkJoinPool class with explanation

Methods

Description

submit()


This method is used to submit a ForkJoinTask for execution.

shutdown()

This method is used to gracefully shut down the pool.

shutdownNow()

This method is used to forcefully shutdown the pool, cancelling all running tasks and discarding any unprocessed tasks.

invoke()

This method is used to wait for and return the result of the given task.

invokeAll()

This method is used to execute a given set of tasks, returning a list of Futures, one for each task, in the order they are returned by the iterator.


execute()


This method is used to execute the given task, possibly in a new thread, returning its result upon completion.

awaitTermination()

This method is used to wait for the termination of the given task.

Create a thread pool using the ForkJoinPool class

Creating a ForkJoinPool is a relatively expensive operation, so you should avoid creating multiple instances of the class in your application.

Example

Let's see how to create a thread pool:

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask; 

public class ForkJoinPoolExample { 
  public static void main(String[] args) { 
    
    // Create a ForkJoinPool with the specified parallelism level
    ForkJoinPool forkJoinPool = new ForkJoinPool(4);
    
    // submit tasks to be executed by the pool 
    ForkJoinTask<Integer> task = 
      forkJoinPool.submit(() -> {
          int result = 0;
          for (int i = 1; i <= 10; i++) {
              result += i;          
          }
          return result;
      });

    // Wait for the task to complete
    try {
        System.out.println("Result: " + task.get());
    } catch (Exception e) {
        e.printStackTrace();
    }

    // shutdown the pool 
    forkJoinPool.shutdown(); 
  } 
}
creating a fork join pool using ForkJoinPool class in Java

Explanation

  • Line 1–2: We import the ForkJoinPool and ForkJoinTask classes from the java.util.concurrent package.
  • Line 8: We create a ForkJoinPool instance by calling the constructor that accepts an int argument, passing in 4 as the argument. This will create a ForkJoinPool with four worker threads.
  • Line 11: We create a ForkJoinTask by invoking the submit() method on our ForkJoinPool. The submit() method takes a Supplier<T> object as an argument. In our case, we pass in a lambda expression We have submitted a task to the pool that calculates the sum of numbers from 1 to 10 and returns the result as an int value.
  • Line 21-24: The get() method returns the result of the task. If the task completes successfully, we print out the result. Otherwise, we'll catch any exceptions that were thrown and print out the stack trace.

When we run the program, we will see the following output:

Result: 55

You can also use the invoke() or invokeAll() methods to submit a collection of tasks to the ForkJoinPool. The invoke() method waits for the specified task to complete before returning, while the invokeAll() method returns when all the tasks in the collection have completed.

You can reuse an existing ForkJoinPool instance by submitting tasks to it using the submit() method.

When you are finished with a ForkJoinPool instance, you should shut it down using the shutdown() method. This will allow the worker threads to terminate gracefully.

Conclusion

In this article, we learned how to create a thread pool using ForkJoinPool class in Java. We also learned how to submit tasks to the pool and wait for the tasks to complete. Finally, we learned how to shutdown the pool using the shutdown() method.

RELATED TAGS

java
thread pool
RELATED COURSES

View all Courses

Keep Exploring