ThreadPoolExecutor allowCoreThreadTimeOut Idle Shrink
prestartAllCoreThreads warms core threads and allowCoreThreadTimeOut lets idle ones exit after the keep-alive window, so the pool can shrink back to zero.
Code
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ElasticCorePool {
public static void main(String[] args) throws InterruptedException {
// 核心 2、上限 6;allowCoreThreadTimeOut 要求 keep-alive > 0
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 6, 300, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
// prestartAllCoreThreads:立刻把核心线程拉起来等活,而不是等第一个任务
System.out.println("prestarted: " + pool.prestartAllCoreThreads());
System.out.println("pool size before work: " + pool.getPoolSize());
// 默认核心线程常驻;打开后空闲的核心线程也按 keep-alive 超时退出
pool.allowCoreThreadTimeOut(true);
for (int i = 0; i < 5; i++) {
final int id = i;
pool.execute(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("task " + id + " done");
});
}
pool.shutdown();
pool.awaitTermination(2, TimeUnit.SECONDS);
// 任务跑完后继续空闲超过 keep-alive:核心线程也退出,池缩到 0
Thread.sleep(600);
System.out.println("pool size after idle: " + pool.getPoolSize());
}
}Inside the snippet
Under the hood: the class ElasticCorePool.
The loop for (int i = 0; i < 5; i++) is the only repeated construct.
Watch out for
- Copy, run: the standard library answers every call in the file.
Putting it to use
The file’s steps are announced right in the output: prestarted:, pool size before work:, task.
The core lines of the flow
Thread.currentThread().interrupt();
pool.allowCoreThreadTimeOut(true);
Thread.sleep(100);
Interactive Tools for This Topic
FAQ
- What does ThreadPoolExecutor allowCoreThreadTimeOut Idle Shrink print when run?
- The script runs standalone; its 4 labeled outputs include `prestarted:`, `pool size before work:`, `task`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.