7

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 ?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
Tony
  • 1,214
  • 14
  • 18

1 Answers1

9

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.

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • It is not working for me. I am using visual vm to view the thread pool size and It is always displaying initial pool size that has been set. – Innovation Jan 30 '17 at 10:58
  • Post a new question with code to analyse the issue. – Ravindra babu Jan 31 '17 at 02:01
  • You also need to set maxPoolSize() after creation of newFixedThreadPool.If you were not doing that then in that case maxPoolSize value will be set to the value assigned to newFixedThreadPool and Afterwards if you want to setCorePoolSize to something greater then the newFixedThreadPool then it will not take the new pool size because in that case it will be greater then the maxPoolSize. – Innovation Jan 31 '17 at 03:52