具有单个线程池比多个线程池更好的设计 [英] Is having a single threadpool better design than multiple threadpools

查看:132
本文介绍了具有单个线程池比多个线程池更好的设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中拥有多个线程池的优点和缺点是什么?我已经看过代码,其中有多个线程池用于不同的类型"任务,并且我不确定是更好的设计还是只是开发人员感到懒惰.一个示例是使用 ScheduledThreadPoolExecutor 定期执行的任务或具有超时的任务,并使用其他ThreadPoolExecutor进行其他所有操作.

What are the advantages and disadvantages of having more than one threadpool in Java? I have seen code where there are multiple threadpools for different "types" of tasks, and I'm not sure whether its better design or just developers being lazy. One example is using a ScheduledThreadPoolExecutor for tasks that are executed periodically or have a timeout, and use another ThreadPoolExecutor for everything else.

推荐答案

拥有单独的专用线程池的目的是,使活动不会因线程不足而被饥饿,因为其他活动占用了所有线程.如果某个服务有自己的线程池,那么可以确保有一定数量的线程可供使用,并且对其他服务的需求不那么敏感.

The purpose of having separate dedicated threadpools is so that an activity doesn't get starved for threads because other activities took all the threads. If some service has its own threadpool then it is assured of having a certain number of threads at its disposal and it's not as sensitive to demands made by other services.

使用多个专用线程池时,如果服务需要太多线程,则它必须等待线程可用,从而将背压引入系统,以使其逐渐降低,并且由于其他部分具有自己的线程池,因此它们具有有机会赶上他们的部分.因此,想法是随着负载的变化,系统应具有更稳定的特性.在您描述为计划的任务使用单独的线程池的情况下,请确保无论系统其余部分有多忙,这些任务都可以运行.

With the multiple dedicated threadpools if a service needs too many threads then it has to wait for threads to be available, introducing back-pressure into the system so that it degrades gradually, and since other parts have their own thread pools they have a chance to catch their parts up. So the idea is that the system should have more stable characteristics as load changes. In the case you describe having a separate threadpool for scheduled tasks makes sure that those tasks get run regardless of how busy the rest of the system is.

多个线程池将需要进行调整,以确保每个池都有足够的线程而不是太多.使用单个线程池,您不需要调整,有时可能会更好地利用所有线程,但是您可能无法预测某些重要任务会及时获取需要完成的线程.

The multiple threadpools would require tuning to make sure each pool had enough threads and not too many. With a single threadpool you wouldn't need the tuning and might make better use of all the threads sometimes, but you might not have the predictability of knowing some important task would get the threads it needed to finish in a timely manner.

这篇关于具有单个线程池比多个线程池更好的设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆