I have a example code.
@Test
public void testWithBlockQueue() throws InterruptedException {
String poolFormat = "ServiceTaskPool-%d";
int coreSize = 3;
int maxSize = 3;
int queueSize = 1;
int idleThreadLiveInSecond = 35;
ThreadFactory factory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
};
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(queueSize);
final ThreadPoolExecutor service = new ThreadPoolExecutor(coreSize, maxSize, idleThreadLiveInSecond,
TimeUnit.SECONDS, queue, factory, new ThreadPoolExecutor.AbortPolicy());
service.allowCoreThreadTimeOut(true);
passTask(coreSize, service);
Thread.sleep(5000);
passTask(coreSize, service);
System.out.printf("Thread pool state %s", service);
Thread.sleep(6000);
}
protected void passTask(int coreSize, ThreadPoolExecutor service) {
for (int i=0; i < coreSize; i++) {
service.execute(new Runnable() {
@Override
public void run() {
System.out.printf("Simple printf from %s \n", Thread.currentThread().getName());
}
});
}
}
When I set queueSize 2, I got exception because threadpoolexecutor can not insert one task to queue, when I set queueSize 3 is ok. I don't understant why when I set maxSize = 4, test is ok. It's from documentation.
- If the number of threads is less than the corePoolSize, create a new Thread to run a new task.
- If the number of threads is equal (or greater than) the corePoolSize, put the task into the queue.
- If the queue is full, and the number of threads is less than the maxPoolSize, create a new thread to run tasks in.
- If the queue is full, and the number of threads is greater than or equal to maxPoolSize, reject the task.