views:

299

answers:

2

I have a java.util.concurrent.Execution service - a single threaded thread pool executor. I submit certain tasks to it. If the task throws an unchecked exception the thread dies but the service ensures that a new thread is spawned and subsequent tasks are performed in that. However I do not want this feature and still want to use a threadPoolExecutor. i.e. I want the service to shutDownNow() if the task throws an unchecked exception.

What is the best way to achieve this? Would using a custom thread factory which restricts the number of threads spawned make good sense?

+2  A: 

You could wrap your threadPoolExecutor in an ExecutorCompletionService. Then continually take() from it, retrieving Futures. If future.get() throws an Exception, call threadpoolexecutor.shutdown().

Apocalisp
I found this very useful when running multiple threads using a ScheduledThreadPoolExecutor under JUnit when compared to overriding the afterExecute() method because the Throwable argument to that method was always null for some reason.
BD at Rivenhill
+2  A: 

You can create a ThreadPoolExecutor subclass and override the afterExecute method. The method has a throwable parameter that will be non-null if there was an exception.

CurtainDog