线程池Executors使用的坑,内存泄漏

  案例代码:

  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);

  运行一段时间后,主机内存告警,直至OOM

  仔细分析一下问题:

 newFixedThreadPool 内部实现的阻塞队列new LinkedBlockingQueue<Runnable>() 采用的有界队列

 当线程池使用过程中,线程数已经达到MaxThread,任务将不断添加到LinkedBlockingQueue阻塞队列中,当硬件配置吃紧,直接导致OOM。

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }


public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);  //初始值太大
}
 
public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    // 任务阻塞队列的初始容量
    this.capacity = capacity;
    last = head = new Node<E>(null);

猜你喜欢

转载自blog.csdn.net/jason_jiahongfei/article/details/113036810