The ForkJoinPool class is the center of the fork/join framework, which is an implementation of the ExecutorService interface. ForkJoinPool class is an extension of the AbstractExecutorService class, and it implements the work-stealing algorithm (i.e., worker threads that run out of things to do can steal tasks from other threads that are still busy) of fork/join framework and can execute ForkJoinTask processes.
The ForkJoinPool class inherits the following methods from java.util.concurrent.AbstractExecutorService class:
- invokeAll()
- invokeAny()
The ForkJoinPool class inherits the following methods from Methods inherited from class java.lang.Object class:
- clone()
- equals()
- finalize()
- getClass()
- hashCode()
- notify()
- notifyAll()
- wait()
Syntax:
public class ForkJoinPool extends AbstractExecutorService
Fork: Fork step splits the task into smaller subtasks and these tasks are executed concurrently.
Join: After the execution of the subtasks, the task may join all the results into one result.
This is illustrated in the diagram below:
Example:
getActiveThreadCount(): This method returns an estimated number of threads that are currently stealing or executing tasks. It may overestimate the number of active threads.
Syntax
public int getActiveThreadCount()
Java
// Java program to demonstrate the // Implementation of getActiveThreadCount() import java.util.ArrayList; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; class NewTask extends RecursiveAction { private long Load = 0 ; public NewTask( long Load) { this .Load = Load; } protected void compute() { // fork tasks into smaller subtasks List<NewTask> subtasks = new ArrayList<NewTask>(); subtasks.addAll(createSubtasks()); for (RecursiveAction subtask : subtasks) { subtask.fork(); } } // function to create and add subtasks private List<NewTask> createSubtasks() { // create subtasks List<NewTask> subtasks = new ArrayList<NewTask>(); NewTask subtask1 = new NewTask( this .Load / 2 ); NewTask subtask2 = new NewTask( this .Load / 2 ); NewTask subtask3 = new NewTask( this .Load / 2 ); // to add the subtasks subtasks.add(subtask1); subtasks.add(subtask2); subtasks.add(subtask3); return subtasks; } } public class JavaForkJoingetActivethreadcountExample1 { public static void main( final String[] arguments) throws InterruptedException { // get no. of available core available int proc = Runtime.getRuntime().availableProcessors(); System.out.println( "Number of available core in the processor is: " + proc); // get no. of threads active ForkJoinPool Pool = ForkJoinPool.commonPool(); System.out.println( "Number of active thread before invoking: " + Pool.getActiveThreadCount()); NewTask t = new NewTask( 400 ); Pool.invoke(t); System.out.println( "Number of active thread after invoking: " + Pool.getActiveThreadCount()); System.out.println( "Common Pool Size is: " + Pool.getPoolSize()); } } |
Number of available core in the processor is: 4 Number of active thread before invoking: 0 Number of active thread after invoking: 3 Common Pool Size is: 3
Methods of ForkJoinPool Class
METHOD |
DESCRIPTION |
---|---|
public boolean awaitQuiescence(long timeout, TimeUnit unit) | This method executes pool until the pool is quiescent, otherwise, assist performing tasks until specified time value and unit elapses or the pool is quiescent. |
public boolean awaitTermination(long timeout, TimeUnit unit) | This method blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. |
public static ForkJoinPool commonPool() | This method returns the common pool instance. |
public void execute(Runnable task) | This method executes the given command at some time in the future. |
public int getActiveThreadCount() | This method returns an estimated number of threads that are currently stealing or executing tasks. It may overestimate the number of active threads. |
public boolean getAsyncMode() | This method returns true if this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined. |
public static int getCommonPoolParallelism() | This method returns the targeted parallelism level of the common pool. |
public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory() | This method returns the factory used for constructing new workers. |
public int getParallelism() | This method returns the targeted parallelism level of this pool. |
public int getPoolSize() | This method returns the number of worker threads that have started but not yet terminated. |
public int getQueuedSubmissionCount() | This method returns an estimate of the number of tasks submitted to this pool that have not yet begun executing. |
public long getQueuedTaskCount() | This method returns an estimate of the total number of tasks currently held in queues by worker threads |
public int getRunningThreadCount() | This method returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization. |
public long getStealCount() | This method returns an estimate of the total number of tasks stolen from one thread’s work queue by another. |
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() | This method returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. |
public boolean hasQueuedSubmissions() | This method returns true if there are any tasks submitted to this pool that have not yet begun executing. |
public <T> T invoke(ForkJoinTask<T> task) | This method performs the given task and returns its result upon completion. |
public boolean isQuiescent() | This method returns true if all worker threads are currently idle. |
public boolean isShutdown() | This method returns true if the pool calling isShutdown() has been shut down. |
public boolean isTerminated() | This method returns true if all tasks have completed following shut down. |
public boolean isTerminating() | This method returns true if the process of termination has started but not yet completed. |
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) | This method returns a RunnableFuture which, when run, will call the underlying callable and which, as a Future, will yield the callable’s result as its result and provide for cancellation of the underlying task. |
public void shutdown() | This method returns true if this pool has been shut down. |
public List<Runnable> shutdownNow() | This method possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. |
public ForkJoinTask<?> submit(Runnable task) | This method submits a Runnable task for execution and returns a Future representing that task. |
public String toString() | This method returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts. |