Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...