Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Thread Pool

I have a long running process that listens to events and do some intense processing.

Currently I use Executors.newFixedThreadPool(x) to throttle the number of jobs that runs concurrently, but depending of the time of the day, and other various factors, I would like to be able to dynamically increase or decrease the number of concurrent threads.

If I decrease the number of concurrent threads, I want the current running jobs to finish nicely.

Is there a Java library that let me control and dynamically increase or decrease the number of concurrent threads running in a Thread Pool ? (The class must implement ExecutorService).

Do I have to implement it myself ?

like image 942
Tony Avatar asked Sep 11 '15 15:09

Tony


1 Answers

Have a look at below API in ThreadPoolExecutor

public void setCorePoolSize(int corePoolSize)

Sets the core number of threads. This overrides any value set in the constructor.

If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle.

If larger, new threads will, if needed, be started to execute any queued tasks.

Initialization:

ExecutorService service = Executors.newFixedThreadPool(5); 

On need basis, resize Thread pool by using below API

((ThreadPoolExecutor)service).setCorePoolSize(newLimit);//newLimit is new size of the pool 

Important note:

If the queue is full, and new value of number of threads is greater than or equal to maxPoolSize defined earlier, Task will be rejected.

So set values of maxPoolSize and corePoolSize properly.

like image 121
Ravindra babu Avatar answered Nov 07 '22 14:11

Ravindra babu