How it works...

The ForkJoinTask class provides the cancel() method that allows you to cancel a task if it hasn't been executed yet. This is a very important point. If the task has begun its execution, a call to the cancel() method has no effect. The method receives a parameter as a Boolean value called mayInterruptIfRunning. This name may make you think that, if you pass the true value to the method, the task will be canceled even if it is running. The Java API documentation specifies that, in the default implementation of the ForkJoinTask class, this attribute has no effect. The tasks are only canceled if they haven't started their execution. The cancellation of a task has no effect over the tasks that the cancelled task sent to the pool. They continue with their execution.

A limitation of the fork/join framework is that it doesn't allow the cancellation of all the tasks that are in ForkJoinPool. To overcome that limitation, you implemented the TaskManager class. It stores all the tasks that have been sent to the pool. It has a method that cancels all the tasks it has stored. If a task can't be canceled because it's running or has finished, the cancel() method returns the false value, so you can try to cancel all the tasks without being afraid of the possible collateral effects.

In the example, you have implemented a task that looks for a number in an array of numbers. You divided the problem into smaller subproblems as the fork/join framework recommends. You are only interested in one occurrence of the number, so when you find it, you cancel the other tasks.

The following screenshot shows part of an execution of this example:

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

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