Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ForkJoinPool.commonPool() and new ForkJoinPool(availableCPU - 1)?

In my code, I have a class containing a static final variable

private static final ForkJoinPool pool = new ForkJoinPool(availableCPUs - 1);

I have a long running task submitted to the pool, which would take all the CPU resource. Any other tasks submitted would be hanging. However, when I switched to create a common pool

private static final ForkJoinPool pool = ForkJoinPool.commonPool();

All the tasks can be submitted and executed.

I was just wondering what the differences are between these two pieces of code. commonPool() still calls new ForkJoinPool() and passes the availableCPUs - 1

Also I noticed that commonPool() uses a factory of type SafeForkJoinWorkerThreadFactory while new ForkJoinPool() uses ForkJoinPool$DefaultForkJoinWorkerThreadFactory. Does this matter?

Thank you very much!

like image 790
klabe Avatar asked May 29 '26 05:05

klabe


1 Answers

I think I figured it out.

ForkJoin maintains two types of queues: one general inbound queue and worker thread queues for each worker thread. All worker threads will fetch from the general inbound queue first and populate their worker threads. After one worker thread finishes all the tasks in its worker queue, it will try to steal from other worker threads. If there no other task to steal from other worker threads, the work thread will fetch from the general inbound queue again.

However, with common pool, the main thread will also help to process the tasks. The main thread does not have a worker queue though. Therefore, after finishing one task, the main thread will be able to fetch from general inbound queue.

Since by default, the ForkJoin queues are LIFO, the main thread will be able the fetch the last submitted tasks.

like image 140
klabe Avatar answered Jun 01 '26 08:06

klabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!