700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 为什么阿里巴巴Java开发手册中不允许用Executors去创建线程池?

为什么阿里巴巴Java开发手册中不允许用Executors去创建线程池?

时间:2023-03-03 10:14:23

相关推荐

为什么阿里巴巴Java开发手册中不允许用Executors去创建线程池?

在我阅读阿里巴巴开发手册的时候,有一段关于多线程的描述:

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

当看到不允许使用Executors创建线程池的时候,我有点懵,仔细一看不无道理。

我们来逐个分析。

FixedThreadPool 和 SingleThreadPool

这两个线程池是线程池大小是固定的。SingleThreadPool是单个线程的线程池。FixedThreadPool在应对平稳流量的时候,能有效的处理,缺点就是可能无法应付突发性大流量。

使用Executors创建:

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

我们点开方法看一下:

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

两个方法,都通过了 LinkedBlockingQueue<Runnable>来接收来不及处理的任务。关键点就在这个队列里,默认的构造器容量是Integer.MAX_VALUE。

public LinkedBlockingQueue() {this(Integer.MAX_VALUE);}

那就是说,当流量突然变得非常大时,线程池满,等候队列变得非常庞大,内存和CPU都告急,这样无疑对服务器造成非常大的压力。

CachedThreadPool 和 ScheduledThreadPool

ExecutorService cacheThreadPool = Executors.newCachedThreadPool();public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);}public ScheduledThreadPoolExecutor(int corePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());}

同理,从工厂方法可以看到,这两种线程池,线程池大小是不固定的,虽然newScheduledThreadPool传如一个线程数,但是这个数字只是核心线程数,可能还会扩容,直至Integer.MAX_VALUE。而他们使用的队列是SynchronousQueue和DelayedWorkQueue。这两个队列我没有细看,但初始化时不会像LinkedBlockingQueue那样一下子将容量调整到最大。

总结:阿里手册希望程序员们根据业务情况,通过ThreadPoolExecutor手动地去创建线程池,线程池大小应该有个边界,并选取合适的队列存储任务。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。