关于java:java并发动态调整线程池

10次阅读

共计 2084 个字符,预计需要花费 6 分钟才能阅读完成。

为什么要动静调整

实践公式计算出的参数不能满足不同业务零碎的需要,于是采取动静调整线程池各个参数来不便调优寻找更适合的设置。

什么能够动静调整

温习一下几个参数

1、corePoolSize:the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set
(外围线程数大小:不论它们创立当前是不是闲暇的。线程池须要放弃 corePoolSize 数量的线程,除非设置了 allowCoreThreadTimeOut。)
2、maximumPoolSize:the maximum number of threads to allow in the pool。
(最大线程数:线程池中最多容许创立 maximumPoolSize 个线程。)
3、keepAliveTime:when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating。
(存活工夫:如果通过 keepAliveTime 工夫后,超过外围线程数的线程还没有承受到新的工作,那就回收。)
4、unit:the time unit for the {@code keepAliveTime} argument
(keepAliveTime 的工夫单位。)
5、workQueue:the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method。
(寄存待执行工作的队列:当提交的工作数超过外围线程数大小后,再提交的工作就寄存在这里。它仅仅用来寄存被 execute 办法提交的 Runnable 工作。所以这里就不要翻译为工作队列了,好吗?不要本人给本人挖坑。)
6、threadFactory:the factory to use when the executor creates a new thread。
(线程工程:用来创立线程工厂。比方这外面能够自定义线程名称,当进行虚拟机栈剖析时,看着名字就晓得这个线程是哪里来的,不会懵逼。)
7、handler:the handler to use when execution is blocked because the thread bounds and queue capacities are reached。
(回绝策略:当队列外面放满了工作、最大线程数的线程都在工作时,这时持续提交的工作线程池就解决不了,应该执行怎么样的回绝策略。)

温习一下执行流程

1、首先检测线程池运行状态,如果不是 RUNNING,则间接回绝,线程池要保障在 RUNNING 的状态下执行工作。
2、如果 workerCount < corePoolSize,则创立并启动一个线程来执行新提交的工作。
3、如果 workerCount >= corePoolSize,且线程池内的阻塞队列未满,则将工作增加到该阻塞队列中。
4、如果 workerCount >= corePoolSize && workerCount < maximumPoolSize,且线程池内的阻塞队列已满,则创立并启动一个线程来执行新提交的工作。
5、如果 workerCount >= maximumPoolSize,并且线程池内的阻塞队列已满, 则依据回绝策略来解决该工作, 默认的解决形式是间接抛异样。

为什么能够动静调整

1、JDK 容许线程池应用方通过 ThreadPoolExecutor 的实例来动静设置线程池的外围策略,以 setCorePoolSize 为办法例,在运行期线程池应用方调用此办法设置 corePoolSize 之后,线程池会间接笼罩原来的 corePoolSize 值,并且基于以后值和原始值的比拟后果采取不同的解决策略。对于以后值小于当前工作线程数的状况,阐明有多余的 worker 线程,此时会向以后 idle 的 worker 线程发动中断请求以实现回收,多余的 worker 在下次 idle 的时候也会被回收;对于以后值大于原始值且以后队列中有待执行工作,则线程池会创立新的 worker 线程来执行队列工作。
2、 线程池外部会解决好以后状态做到平滑批改 ,基于这几个 public 办法,咱们只须要保护 ThreadPoolExecutor 的实例,并且在须要批改的时候拿到实例批改其参数即可。

实现计划

corePoolSize、maximumPoolSize、keepAliveTime 间接通过音讯 / 配置批改,而队列容量能够重写 LinkedBlockingQueue 并把 capacity 设置为非 final。

参考

https://segmentfault.com/a/11…
https://mp.weixin.qq.com/s/Yb…
https://www.javadoop.com/post…

正文完
 0