在具有等待任务时动态调整java.util.concurrent.ThreadPoolExecutor的大小 [英] Dynamic resizing of java.util.concurrent.ThreadPoolExecutor while it has waiting tasks

查看:109
本文介绍了在具有等待任务时动态调整java.util.concurrent.ThreadPoolExecutor的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java.util.concurrent.ThreadPoolExecutor 来并行处理多个项目。尽管线程本身工作正常,但由于线程中发生的操作,我们有时会遇到其他资源限制,这使我们想要调低池中线程的数量。

I'm working with a java.util.concurrent.ThreadPoolExecutor to process a number of items in parallel. Although the threading itself works fine, at times we've run into other resource constraints due to actions happening in the threads, which made us want to dial down the number of Threads in the pool.

我想知道在线程实际工作时是否有办法拨打线程数。我知道你可以调用 setMaximumPoolSize()和/或 setCorePoolSize(),但这些只调整一次线程池变得空闲,但是在队列中没有任务等待之前它们不会空闲。

I'd like to know if there's a way to dial down the number of the threads while the threads are actually working. I know that you can call setMaximumPoolSize() and/or setCorePoolSize(), but these only resize the pool once threads become idle, but they don't become idle until there are no tasks waiting in the queue.

推荐答案

尽我所能告诉我,这是不可能的一个很好的干净方式。

As far as I can tell, this is not possible in a nice clean way.

您可以实现beforeExecute方法来检查一些布尔值并强制线程暂时停止。请记住,它们将包含一个在重新启用之前不会执行的任务。

You can implement the beforeExecute method to check some boolean value and force threads to halt temporarily. Keep in mind, they will contain a task which will not be executed until they are re-enabled.

或者,您可以实现afterExecute在饱和时抛出RuntimeException 。这将有效地导致Thread死亡,并且由于Executor将高于最大值,因此不会创建新的。

Alternatively, you can implement afterExecute to throw a RuntimeException when you are saturated. This will effectively cause the Thread to die and since the Executor will be above the max, no new one would be created.

我不建议你这样做。相反,尝试找到一些其他方法来控制导致问题的任务的并发执行。可能是在一个单独的线程池中执行它们,并且工作人员数量有限。

I don't recommend you do either. Instead, try to find some other way of controlling concurrent execution of the tasks which are causing you a problem. Possibly by executing them in a separate thread pool with a more limited number of workers.

这篇关于在具有等待任务时动态调整java.util.concurrent.ThreadPoolExecutor的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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