How do I create a ThreadPoolExecutor, create threads as needed and expire them when applicable?
My use case:
>Set the minimum size "n" for the thread pool, which means that "n" threads are always available after the executor starts. > Set the maximum size "m" for the thread pool. > When all "m" threads are busy, incoming tasks should be queued. > Expire (M - n) threads based on idle timeout
I believe the pool manager behind httpclient can make similar settings I'm trying to implement it using ThreadPoolExecutor, but I can't find a way Is it possible?
This is an example of a test
public class ExecutorExample {
public static void main(String[] args) throws InterruptedException {
int minPoolSize = 2;
int maxPoolSize = 10;
int ttlMillis = 100;
ThreadPoolExecutor startupExecutor = new ThreadPoolExecutor(minPoolSize,maxPoolSize,// surprisingly this is not obeyed.
ttlMillis,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
startupExecutor.execute(new MyRunnable(i));
}
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
}
}
}
class MyRunnable implements Runnable {
int n;
public MyRunnable(int n) {
this.n = n;
}
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":" + n);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Solution
How's this?
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue);
ThreadPoolExecutor
Edit: the queue I usually use is bounded blocking queue
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(queueCapacity,true);
Edit2: the maximum pool size starts only when the queue is full Because you are using unbounded queues, the number of threads will not be higher than 2 The se link is as follows
rules-of-a-threadpoolexecutor-pool-size
Zoom in size 1 and you'll see the difference
new LinkedBlockingQueue<>(1));
Edit 3: in your example, use startupexecution Getpoolsize() change startupexecution getCorePoolSize().
