为何阿里巴巴要禁用Executors建立线程池?看阿里巴巴开发手册并发编程这块有一条:线程池不容许使用Executors去建立,而是经过ThreadPoolExecutor的方式,经过源码分析禁用的缘由
管理一组工做线程。经过线程池复用线程有如下几点优势:java
OutOfMemoryError
【简称OOM】根据返回的对象类型建立线程池能够分为三类:编程
由于这些建立线程池的静态方法都是返回ThreadPoolExecutor
对象,和咱们手动建立ThreadPoolExecutor
对象的区别就是咱们不须要本身传构造函数的参数。ThreadPoolExecutor
的构造函数共有四个,但最终调用的都是同一个:缓存
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
构造函数参数说明:并发
<img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggm9avnt4pj30lp0ak74g.jpg" alt="image-20200205095809050" style="zoom:50%;" />ide
执行逻辑说明:函数
corePoolSize
参数有关,未满则建立线程执行任务workQueue
参数有关,若未满则加入队列中maximumPoolSize
参数有关,若未满建立线程执行任务handler
参数有关Executors
建立返回ThreadPoolExecutor对象的方法共有三种:工具
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
CachedThreadPool
是一个根据须要建立新线程的线程池当一个任务提交时,corePoolSize
为0不建立核心线程,SynchronousQueue
是一个不存储元素的队列,能够理解为队里永远是满的,所以最终会建立非核心线程来执行任务。对于非核心线程空闲60s时将被回收。**由于Integer.MAX_VALUE
很是大,能够认为是能够无限建立线程的,在资源有限的状况下容易引发OOM异常源码分析
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
SingleThreadExecutor
是单线程线程池,只有一个核心线程post
当一个任务提交时,首先会建立一个核心线程来执行任务,若是超过核心线程的数量,将会放入队列中,由于LinkedBlockingQueue
是长度为Integer.MAX_VALUE
的队列,能够认为是无界队列,所以往队列中能够插入无限多的任务,在资源有限的时候容易引发OOM
异常,同时由于无界队列,maximumPoolSize
和keepAliveTime
参数将无效,压根就不会建立非核心线程性能
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
FixedThreadPool
是固定核心线程的线程池,固定核心线程数由用户传入
SingleThreadExecutor
相似,惟一的区别就是核心线程数不一样,而且因为**使用的是LinkedBlockingQueue
,在资源有限的时候容易引发OOM
异常OOM
异常OOM
异常public class TaskTest { public static void main(String[] args) { ExecutorService es = Executors.newCachedThreadPool(); int i = 0; while (true) { es.submit(new Task(i++)); } } }
使用Executors
建立的CachedThreadPool
,往线程池中无限添加线程 在启动测试类以前先将JVM
内存调整小一点,否则很容易将电脑跑出问题,在idea
里:Run
-> Edit Configurations
<img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggm9iwblb8j30tw0i60tn.jpg" alt="image-20200205095809050" style="zoom:50%;" />
建立到3w多个线程的时候开始报OOM
错误
另外两个线程池就不作测试了,测试方法一致,只是建立的线程池不同
<img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggm9ugaj8ij315c0juaaq.jpg" alt="image-20200205095809050" style="zoom:30%" />
CPU
数量 + 1,CPU
数量能够根据Runtime.availableProcessors
方法获取CPU
数量 CPU
利用率 (1 + 线程等待时间/线程CPU时间)CPU
密集型和IO
密集型,而后分别使用不一样的线程池去处理,从而使每一个线程池能够根据各自的工做负载来调整拒绝策略 => 默认采用的是AbortPolicy拒绝策略,直接在程序中抛出 RejectedExecutionException 异常【由于是运行时异常,不强制catch】,这种处理方式不够优雅。处理拒绝策略有如下几种比较推荐:
RejectedExecutionException
异常,在捕获异常中对任务进行处理。针对默认拒绝策略CallerRunsPolicy
拒绝策略,该策略会将任务交给调用execute的线程执行【通常为主线程】,此时主线程将在一段时间内不能提交任何任务,从而使工做线程处理正在执行的任务。此时提交的线程将被保存在TCP
队列中,TCP队列满将会影响客户端,这是一种平缓的性能下降RejectedExecutionHandler
接口便可DiscardPolicy
和DiscardOldestPolicy
拒绝策略将任务丢弃也是能够的若是使用Executors的静态方法建立ThreadPoolExecutor
对象,能够经过使用Semaphore
对任务的执行进行限流也能够避免出现OOM
异常
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build() ); executorService.execute(() -> System.out.println("run"));
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build(); ExecutorService executor = new ThreadPoolExecutor( 5, 200, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy() ); executor.submit(() -> System.out.println(Thread.currentThread().getName() + "run")); executor.shutdown();
https://juejin.im/post/5dc41c...
https://my.oschina.net/u/4440...
本文由博客群发一文多发等运营工具平台 OpenWrite 发布