Java并发系列(13)

您所在的位置:网站首页 并发线程数多少合适 Java并发系列(13)

Java并发系列(13)

2024-05-24 08:46| 来源: 网络整理| 查看: 265

接上一篇《Java并发系列(12)——ForkJoin框架源码解析(下)》

9.5 线程池的选择与参数设置9.5.1 JDK 预定义的线程池9.5.1.1 Executors#newCachedThreadPoolpublic static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); }

只传了 5 个参数,线程工厂和拒绝策略没有传。线程工厂不影响性能,拒绝策略比较重要。

拒绝策略不传就是默认,默认是 AbortPolicy,拒绝任务时抛异常:

/** * The default rejected execution handler */ private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();

特点:

队列使用了 SynchronousQueue,没有空间,不存储任务;没有任务就没有线程;任务并发量增大,线程不够立刻新建线程;任务并发量降低,线程空闲 60 秒销毁;拒绝策略不会触发,在拒绝策略触发前,程序会因为线程过多先挂掉。

适用场景(各条件为“且”的关系,下同):

任务耗时短;非 cpu 密集型(会占用很多 cpu 资源)任务;并发量时高时低;cpu 资源充足;前提:能扛住高峰期最大并发量,程序不会挂掉。

此处,耗时多短算“短”,并发量多高算“高”,后面会提供一种计算思路。

9.5.1.2 Executors#newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); }

特点:

线程数量固定(除非线程池创建之后又改设置,并且不考虑懒加载的过程);使用了 LinkedBlockingQueue 无界队列,队列容量无限;拒绝策略不会触发,拒绝策略触发前,程序会先因为任务堆积,内存占用过多挂掉。

适用场景:

并发量比较稳定;内存资源充足;前提:偶尔并发激增,能扛住不会挂。9.5.1.3 Executors#newScheduledThreadPoolpublic static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }

特点:

队列使用 DelayedWorkQueue,无界队列;可执行定时任务;线程数量固定(除非线程池创建后又改设置);拒绝策略触发前,任务堆积,内存溢出,程序先挂(但定时任务其实基本不存在任务堆积的问题)。

适用场景:

有定时任务需求。9.5.1.4 Executors#newSingleThreadExecutorpublic static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLI


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3