In my OCP study books (Java 8), they use a ForkJoinPool to start a RecursiveAction. To do some testing I created a simple instance of the RecursiveAction class named TestAction. To start this RecursiveAction I could use the following way (as used in the book):
I found that it is also possible to call the compute method of my RecursiveAction instance directly:
This seems to give the same result. The major difference I see is that the ForkJoinPool has an overloaded constructor to specify the number of CPU-cores used by my RecursiveAction instance.
So, my question is: why are they using the ForkJoinPool class to start the RecursiveAction?
The point of ForkJoinTask is that the task and its recursive tasks are all run within the same ForkJoinPool.
When you call action.compute() directly, it will be executed by the current thread (which is likely not part of a ForkJoinPool) and the recursive tasks that the action consists of will all be executed by ForkJoinPool.commonPool(). This is NOT how ForkJoinTask is supposed to be used, and for that reason the compute() method is declared as protected. The only reason you can call it is because the code you're calling it from is in the same package as the TestAction method. In general, if you're calling a protected method directly, you're doing it wrong.
When you call fjp.invoke(action), the compute() method of the action gets executed by a thread that is part of fjp. All recursive tasks of your action will also be executed by threads that are part of fjp. This is good.
The human mind is a dangerous plaything. This tiny ad is pretty safe: