You die

I have a java.util.concurrent.Execution service, a single-threaded thread pool executor. I give him some tasks. If a task throws an unchecked exception, the thread dies, but the service guarantees that a new thread will be created, and subsequent tasks will be performed in this case. However, I do not want this function and still want to use threadPoolExecutor. those. I want the shutDownNow () service if the task throws an exception that fails the test.

What is the best way to achieve this? Does a custom thread use a factory that limits the number of threads that are created, makes sense?

+4
source share
2 answers

You can subclass ThreadPoolExecutor and override the afterExecute method. The method has a throwable parameter, which will not be null if an exception occurs.

+3
source

You can wrap threadPoolExecutor in an ExecutorCompletionService . Then continuously take() from it, extracting Future s. If future.get() throws an Exception , call threadpoolexecutor.shutdown() .

+2
source

All Articles