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 ?


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.

链接地址: http://www.djcxy.com/p/92042.html

上一篇: Java中的线程

下一篇: 动态线程池