頻繁創建/銷毀線程開銷巨大(每線程 ~1MB 棧內存),且無序併發易導致 OOM。線程池核心價值:
Executor (頂級接口: execute(Runnable))
└─ ExecutorService (生命週期管理、提交任務返回 Future)
├─ ThreadPoolExecutor (核心實現,高度可配置)
├─ ScheduledExecutorService (定時/周期任務)
│ └─ ScheduledThreadPoolExecutor
└─ AbstractExecutorService (默認實現 submit/invokeAll 等)
| 方法 | 特點 | 底層參數 | 風險 |
|---|---|---|---|
newFixedThreadPool(n) | 固定核心線程數,無界隊列 | core=max=n, queue=LinkedBlockingQueue | 請求堆積導致 OOM |
newCachedThreadPool() | 核心 0,最大 Integer.MAX_VALUE,60s 回收空閒 | core=0, max=MAX, queue=SynchronousQueue | 線程數無上限,突發流量撐爆 CPU/內存 |
newSingleThreadExecutor() | 單線程串行,保證任務順序 | core=max=1, queue=LinkedBlockingQueue | 同固定池,隊列無界 |
newScheduledThreadPool(n) | 定時/周期任務專用 | core=n, max=MAX, queue=DelayedWorkQueue | 非核心線程無界 |
阿里巴巴開發手冊強制:不允許使用 Executors 創建線程池,必須通過 ThreadPoolExecutor 自定義,明確佈局隊列大小、拒絕策略、線程命名、異常處理。
public ThreadPoolExecutor(
int corePoolSize, // 核心線程數(常駐)
int maximumPoolSize, // 最大線程數(峰值)
long keepAliveTime, // 非核心線程空閒存活時間
TimeUnit unit, // 時間單位
BlockingQueue workQueue, // 任務隊列
ThreadFactory threadFactory, // 線程工廠(命名、守護、優先級)
RejectedExecutionHandler handler // 拒絕策略
)
ArrayBlockingQueue:有界,公平,需預估峰值。LinkedBlockingQueue:無界(慎用),固定池永不擴容至 maximumPoolSize。SynchronousQueue:零容量,直接移交,cached 池專用。PriorityBlockingQueue:優先級隊列。AbortPolicy(默認):拋 RejectedExecutionException。CallerRunsPolicy:調用者線程執行任務,天然限流,推薦。DiscardPolicy:靜默丟棄。DiscardOldestPolicy:丟棄隊列頭部最老任務。order-process-%d),便於日誌追蹤、Arthas 排查、JStack 分析。public class ThreadPoolConfig {
private static final int CORE = Runtime.getRuntime().availableProcessors() * 2; // IO 密集假設
private static final int MAX = CORE * 2;
private static final int QUEUE_CAP = 1000;
public static ExecutorService createOrderPool() {
return new ThreadPoolExecutor(
CORE, MAX,
60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAP),
new ThreadFactoryBuilder().setNameFormat("order-process-%d").build(), // Guava
new ThreadPoolExecutor.CallerRunsPolicy() // 限流
);
}
}
// Callable 有返回值、可拋異常 Callabletask = () -> { Thread.sleep(1000); return 2 + 3; }; ExecutorService es = Executors.newSingleThreadExecutor(); Future future = es.submit(task); // 同步阻塞獲取結果 try { Integer result = future.get(2, TimeUnit.SECONDS); // 支持超時 System.out.println("Result: " + result); // 5 } catch (TimeoutException e) { future.cancel(true); // 中斷執行中任務 } catch (ExecutionException e) { e.getCause().printStackTrace(); // 任務內部異常 } // 非阻塞輪詢 while (!future.isDone()) { /* 做其他事 */ } Integer result = future.get();
// 相同 key 只計算一次,併發請求共享 Future ConcurrentMap> cache = new ConcurrentHashMap<>(); public String getData(String key) { Future f = cache.get(key); if (f != null) { try { return f.get(); } catch (Exception e) { cache.remove(key); } } Callable task = () -> expensiveCompute(key); FutureTask ft = new FutureTask<>(task); f = cache.putIfAbsent(key, ft); if (f == null) { f = ft; ft.run(); } // 當前線程執行 try { return f.get(); } catch (Exception e) { cache.remove(key); throw new RuntimeException(e); } }
ThreadPoolExecutor 明確七大參數。CallerRunsPolicy,防 OOM 並實現背壓。biz-module-%d,運維排查神器。execute 提交任務需自行 try-catch 或設置 Thread.UncaughtExceptionHandler,否則異常吞沒無日誌。shutdown() → awaitTermination(timeout) → shutdownNow(),處理剩餘任務。