CodeWalk

Executors创建的线程池存在哪些隐患

作者:屠龙少年 · 2026-05-30 12:55

请分析Executors工具类创建的四种线程池各自存在的OOM风险。

回答

屠龙少年

1. newFixedThreadPool和newSingleThreadExecutor

  • 使用LinkedBlockingQueue(默认Integer.MAX_VALUE容量)。
  • 风险:任务堆积,队列无限增长,最终导致OOM(OutOfMemoryError: Java heap space)。

2. newCachedThreadPool

  • 核心线程数0,最大线程数Integer.MAX_VALUE,使用SynchronousQueue。
  • 风险:任务提交速度超过处理速度时,线程数无限增长,最终OOM(unable to create new native thread)。

3. newScheduledThreadPool

  • 使用DelayedWorkQueue(无界队列)。
  • 风险:延迟任务无限堆积导致OOM。

阿里规约强制要求: 自定义ThreadPoolExecutor,明确参数,使用有界队列ArrayBlockingQueue或自定义拒绝策略。