Dynamic resizing of java.util.concurrent.ThreadPoolExecutor while it has waiting tasks

前端 未结 5 482
走了就别回头了
走了就别回头了 2020-12-05 08:02

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

5条回答
  •  醉酒成梦
    2020-12-05 08:42

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

    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.

    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.

提交回复
热议问题