Java Reference
In-Depth Information
else {
Divide the task into subtsaks.
Launch the subtasks asynchronously (the fork stage).
Wait for the subtasks to finish (the join stage).
Combine the results of all subtasks.
}
The following two methods of the
ForkJoinTask
class provide two important features during a task execution:
The
•
fork()
method launches a new subtask from a task for an asynchronous execution.
•
The
join()
method lets a task wait for another task to complete.
Steps in Using the Fork/Join Framework
Using the fork/join framework involves the following five steps.
Step 1: Declaring a Class to Represent a Task
Create a class inheriting from the
RecursiveAction
or
RecursiveTask
class. An instance of this class represents a task
that you want to execute. If the task yields a result, you need to inherit it from the
RecursiveTask
class. Otherwise, you
will inherit it from the
RecursiveAction
class. The
RecursiveTask
is a generic class. It takes a type parameter, which
is the type of the result of your task. A
MyTask
class that returns a
Long
result may be declared as follows:
public class MyTask extends RecursiveTask<Long> {
// Code for your task goes here
}
Step 2: Implementing the compute() Method
The logic to execute your task goes inside the
compute()
method of your class. The return type of the
compute()
method is the same as the type of the result that your task returns. The declaration for the
compute()
method of the
MyTask
class look like the following:
public class MyTask extends RecursiveTask<Long> {
public Long compute() {
// Logic for the task goes here
}
}
Step 3: Creating a Fork/Join Thread Pool
You can create a pool of worker threads to execute your task using the
ForkJoinPool
class. The default constructor
of this class creates a thread of pool, which has the same parallelism as the number of processors available on the
machine.
ForkJoinPool pool = new ForkJoinPool();
Other constructors let you specify the parallelism and other properties of the pool.