• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • Frits Walraven
  • Himai Minh

ForkJoinPool and RecursiveAction

Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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?

Best regards,
Saloon Keeper
Posts: 12992
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:
Thread Boost feature
    Bookmark Topic Watch Topic
  • New Topic