Skip to end of metadata
Go to start of metadata

All tasks in a thread pool must provide a mechanism for notifying the application if they terminate abnormally. Failure to do so cannot cause resource leaks because the threads in the pool are still recycled, but it makes failure diagnosis extremely difficult or impossible.

The best way to handle exceptions at the application level is to use an exception handler. The handler can perform diagnostic actions, clean up and shut down the Java Virtual Machine, or simply log the details of the failure.

Noncompliant Code Example (Abnormal Task Termination)

This noncompliant code example consists of the PoolService class that encapsulates a thread pool and a runnable Task class. The Task.run() method can throw runtime exceptions, such as NullPointerException.

The task fails to notify the application when it terminates unexpectedly as a result of the runtime exception. Moreover, it lacks a recovery mechanism. Consequently, if Task were to throw a NullPointerException, the exception would be ignored.

Compliant Solution (ThreadPoolExecutor Hooks)

Task-specific recovery or cleanup actions can be performed by overriding the afterExecute() hook of the java.util.concurrent.ThreadPoolExecutor class. This hook is called either when a task concludes successfully by executing all statements in its run() method or when the task halts because of an exception. Some implementations may fail to catch java.lang.Error (see Bug ID 6450211 for more information [SDN 2008]). When using this approach, substitute the executor service with a custom ThreadPoolExecutor that overrides the afterExecute() hook:

The terminated() hook is called after all the tasks have finished executing and the Executor has terminated cleanly. This hook can be overridden to release resources acquired by the thread pool, much like a finally block.

Compliant Solution (Uncaught Exception Handler)

This compliant solution sets an uncaught exception handler on behalf of the thread pool. A ThreadFactory argument is passed to the thread pool during construction. The factory is responsible for creating new threads and setting the uncaught exception handler on their behalf. The Task class is unchanged from the noncompliant code example.

The ExecutorService.submit() method can be used (in place of the execute() method) to submit a task to a thread pool and obtain a Future object. When the task is submitted via ExecutorService.submit(), thrown exceptions never reach the uncaught exception handler because the thrown exception is considered to be part of the return status and is consequently wrapped in an ExecutionException and rethrown by Future.get() [Goetz 2006a].

Compliant Solution (Future<V> and submit())

This compliant solution invokes the ExecutorService.submit() method to submit the task so that a Future object can be obtained. It uses the Future object to let the task rethrow the exception so that it can be handled locally.

Furthermore, any exception that prevents doSomething() from obtaining the Future value can be handled as required.


TPS03-J-EX0: This rule may be violated only when the code for all runnable and callable tasks has been audited to ensure that exceptional conditions are impossible. Nonetheless, it remains good practice to install a task-specific or global exception handler to initiate recovery or log any exceptional conditions.

Risk Assessment

Failure to provide a mechanism for reporting that tasks in a thread pool failed as a result of an exceptional condition can make it difficult or impossible to diagnose the problem.




Remediation Cost









To-Do List



Related Guidelines


CWE-392, Missing Report of Error Condition


[API 2014]

Class Thread
Interface ExecutorService

Interface ThreadFactory

[Goetz 2006a]

Chapter 7.3, "Handling Abnormal Thread Termination"



  1. This guideline may be violated if the code for all runnable and callable tasks has been audited to ensure that no exceptional conditions are possible

    This should be an official exception to the rule.

    • ExecutorService.execute() is not what the NCCE should be running; as it does hide exceptions. Should be using ExecutorService.submit() instead.
    • The 1st CS delegates the solution to EXC01-J. I guess that's ok, but the details of the solution are buried there. This should prob be the last CS as the other CS's are more complete.
    • For the Uncaught Exception Handler CS, I would take out the Logger, and just leave the uncaughtException blank, for consistency with the other CS's (they all leave blank exactly what is done when handling the exception). EG:
    • Need a CS that uses a Future<> object, prob a FutureTask<> object. Then you can simply query the Future object if it had an exception.

    Finally, I'd reorder the CS's thus:

    • Future object
    • ThreadPoolExecutor hooks
    • Uncaught exception handler
    • Custom exception reporter
      • Added explicit exception
      • Not sure if I follow why submit() should be used when the current NCE works. Can you elaborate on this?
      • While the details are not here this might be the best way to initiate recovery. We might want to provide such xrefs/classes in the appendix of the TR. Let's defer this change until I gather more inputs. Also note that the second CS is not the best option because of the mentioned bug and the third CS does not work for submit().

      We could split these up as:

      NCE (submit())
      CS (custom exc reporter)
      NCE (execute())
      CS (custom exc reporter)
      CS (ThreadPoolExecutor hooks)
      CS (Uncaught exception handler)

      But then there is more redundancy.

      • I took out the logger
      • Not sure how to poll; the isDone() method returns true when the task completes even when there is an exception. And isCancelled() is for cancellation. Can you suggest a CS?
      1. Thanks for dealing with the issues. I've added a CS utilizing a Future class, as I suggested. I think this resolves all my issues.