Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ExecutorService

How to use an ExecutorService in a way that a central Thread Pool is created for the application at the application level whose pool size will be set according to the number of threads available with the CPU at that time and then the different functionalities of the application use thread from this central pool as per their requirement.

like image 418
Man Avatar asked Feb 23 '26 08:02

Man


2 Answers

As of Java 8, I suggest you use ForkJoinPool.commonPool(). This is the only global thread pool that base Java provides.

Before Java 8, you either keep your own thread pool(s) or use your framework's shareable thread pool(s).

like image 149
acelent Avatar answered Feb 24 '26 20:02

acelent


Bellow is my view:

  • a central Thread Pool?

    Maybe, it's say the Singleton Pattern in Design Pattern, I think it can solve your problem;

  • set according to the number of threads available with the CPU?

    The size of the thread pool isn't exact. In practice, the size depends on the tasks' type be executed by the thread pool. For example, the size can be Runtime.getRuntime().availableProcessors() + 1 if the tasks are CPU intensive, or be Runtime.getRuntime().availableProcessors() * 2 if the tasks are I/O intensive.But these are only basic principles, you should determine the appropriate size by testing your application with some guidelines(such as Little's_law);

  • my suggests:

    In practice, I seldom submit all tasks to only one central threal pool, maybe should group your tasks by type, submit them to the different thread pool, this will be convenient to monitor or tuning the thread pool later.

Hope to help you.

like image 44
haolin Avatar answered Feb 24 '26 22:02

haolin



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!