Canceling a task

When you execute the ForkJoinTask objects in a ForkJoinPool class, you can cancel them before they start their execution. The ForkJoinTask class provides the cancel() method for this purpose. There are some points you have to take into account when you want to cancel a task, which are as follows:

  • The ForkJoinPool class doesn't provide any method to cancel all the tasks it has running or waiting in the pool
  • When you cancel a task, you don't cancel the tasks this task has executed

In this recipe, you will implement an example of the cancellation of ForkJoinTask objects. You will look for the position of a number in an array. The first task that finds the number will cancel the remaining tasks. As that functionality is not ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.