Customizing tasks running in the fork/join framework

The Executor framework separates task creation and its execution. With it, you only have to implement the Runnable objects and use an Executor object. You just need to send the Runnable tasks to the executor and it creates, manages, and finalizes the necessary threads to execute these tasks.

Java 9 provides a special kind of executor in the fork/join framework (introduced in Java 7). This framework is designed to solve problems that can be broken down into smaller tasks using the divide and conquer technique. Inside a task, you have to check the size of the problem you want to resolve; if it's bigger than the established size, you divide the problem into two or more tasks and execute them using the framework. If the size of the problem is smaller than the established size, you resolve the problem directly in the task; optionally, it returns a result. The fork/join framework implements the work-stealing algorithm that improves the overall performance of these kinds of problems.

The main class of the fork/join framework is the ForkJoinPool class. Internally, it has the following two elements:

  • A queue of tasks that are waiting to be executed
  • A pool of threads that execute the tasks

By default, the tasks executed by a ForkJoinPool class are objects of the ForkJoinTask class. You can also send the Runnable and Callable objects to a ForkJoinPool class, but they can't take advantage of all the benefits of the fork/join framework. Normally, you will send one of two subclasses of the ForkJoinTask class to the ForkJoinPool object:

  • RecursiveAction: If your tasks don't return a result
  • RecursiveTask: If your tasks return a result

In this recipe, you will learn how to implement your own tasks for the fork/join framework by implementing a task that extends the ForkJoinTask class. The task you're going to implement measures and writes its execution time in the console so you can control its evolution. You can also implement your own fork/join task to write log information, to get resources used in the tasks, or to postprocess the results of the tasks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.195.225