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 ?

1 Answer 1

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.

3
  • 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, 2017 at 10:58
  • Post a new question with code to analyse the issue. Jan 31, 2017 at 2: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, 2017 at 3:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.