线程池ThreadPoolExecutor--Executors.newFixedThreadPool()

本文深入探讨了线程池ThreadPoolExecutor的工作原理,分析了使用Executors创建线程池的潜在风险,尤其是OOM问题。建议手动配置线程池参数,以避免资源耗尽。

线程池ThreadPoolExecutor

我们可以使用Executor工厂类Executors快速的获取一个ThreadPoolExecutor

   ExecutorService executorService = Executors.newFixedThreadPool(10);

但是如果我们安装了Alibaba Java Coding Guidelines插件会提示我们

线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这
样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool:
允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
2) CachedThreadPool:
允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。

那么为什么不允许使用Executors去创建呢?首先看newFixedThreadPool方法的实现

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

可以看出创建了一个ThreadPoolExecutor类,核心线程池数量和最大线程池数量都是我们初始化的值,但是要注意阻塞队列使用的是new LinkedBlockingQueue() 是一个链表阻塞队列,再去看看链表阻塞队列的构造方法

	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);
    }

链表的长度达到了默认的Integer的最大值。而再看看ThreadPoolExecutor的execute方法

 /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
		int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);

首先渣渣翻译下上门的三步流程

  1. 如果运行的线程小于核心线程,将开启一个新的核心线程执行任务,如果当前执行的线程大于等于核心线程将会把请求任务入队到阻塞队列
  2. 如果阻塞队列已经满了,并且当前线程小于maximumPoolSize将开启新的线程处理
  3. 如果阻塞队列已经满了,并且当前线程大于maximumPoolSize将执行拒绝策略

从上述知道用默认的Executors.newFixedThreadPool(10)会创建一个大小为Integer.MAX_VALUE的请求队列,如果请求量大的话会导致堆积请求,最终可能出现OOM的情况。因此我们最好自己创建线程池。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值