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
.
Code Block | ||
---|---|---|
| ||
final | ||
Wiki Markup | ||
Tasks that run for extended periods of time should provide a notification mechanism to alert upper layers when they terminate abnormally. Failure to do this does not cause any resource leaks because the threads in the pool are still recycled, however, it makes failure diagnosis extremely difficult. The best way to handle exceptions at a global level is to use an exception handler. The handler can perform diagnostic actions, clean-up and shutdown the JVM or simply log the details of the failure. This guideline may be violated if the code for all tasks has been audited to ensure that no exceptions are possible. Nonetheless, it is usually a good practice to install a handler to initiate recovery. Other ways include overriding {{ThreadPoolExecutor}}'s {{afterExecute()}} hook. This hook is called in the event of a a successful execution (completion of {{run()}}) or an exception (as opposed to an error). Similarly, the {{terminated()}} hook is called after the tasks finish executing. It can be overridden to release resources acquired by the thread pool over time, much like a {{finally}} block. h2. Noncompliant Code Example This noncompliant code example consists of class {{PoolService}} that encapsulate a thread pool and a runnable class, {{Task}}. The {{run()}} method of the task can throw runtime exceptions such as the {{NullPointerException}}. {code:bgColor=#FFCCCC} class PoolService { private final ExecutorService pool = Executors.newFixedThreadPool(10); public void doSomething() throws InterruptedException, IOException { pool.execute(new Task()); } } final class Task implements Runnable { @Override public void run() { // ... throw new NullPointerException(); // ... } } {code} |
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:
Code Block | ||
---|---|---|
| ||
final class PoolService { // The values have been hard-coded for brevity ExecutorService pool = new CustomThreadPoolExecutor( 10, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); // ... } class CustomThreadPoolExecutor extends ThreadPoolExecutor { // ... Constructor ... public CustomThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override public void afterExecute(Runnable r, task does not notify upper layers when it terminated unexpectedly because of the runtime exception. Moreover, there is no recovery code. h2. Compliant Solution This compliant solution refactors the task so that it catches {{Throwable}} and forwards it to a custom exception reporter (see [EXC01-J. Use a class dedicated to reporting exceptions] for details on class {{MyExceptionReporter}}). {code:bgColor=#ccccff} // ... public class Task implements Runnable { @Override public void run() { try { // ... throw new NullPointerException(); // ... } catch(Throwable t) { super.afterExecute(r, t); // Execute anyif recovery code (t != null) { MyExceptionReporter.report(t); // Exception occurred, }forward to handler } } {code} {mc} overriding the afterExecute method in ThreadPoolExecutor}} is also suggested {mc} h2. Compliant Solution This compliant solution sets an uncaught exception handler // ... Perform task-specific cleanup actions } @Override public void terminated() { super.terminated(); // ... Perform final clean-up actions } } |
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.
Code Block | ||
---|---|---|
| ||
final for the thread pool. During the construction of the thread pool, a {{ThreadFactory}} is passed. The factory is responsible for creating new threads and setting the uncaught exception handler on their behalf. The class {{Task}} remains the same as the noncompliant code example. {code:bgColor=#ccccff} class PoolService { private static final ThreadFactory factory = new new ExceptionThreadFactory(new MyExceptionHandler()); private static final ExecutorService pool = Executors.newFixedThreadPool(10, factory); public void doSomething() throws InterruptedException, IOException { pool.execute(new Task()); // Task is a runnable class } public static class ExceptionThreadFactory implements ThreadFactory { private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); private final Thread.UncaughtExceptionHandler handler; public ExceptionThreadFactory( Thread.UncaughtExceptionHandler handler) { this.handler = handler; } @Override public Thread newThread(Runnable run) { Thread thread = defaultFactory.newThread(run); thread.setUncaughtExceptionHandler(handler); return thread; } } public static class MyExceptionHandler extends ExceptionReporter implements Thread.UncaughtExceptionHandler { private final Logger logger = Logger.getLogger("com.organization.Log"); // ... @Override public void uncaughtException(Thread thread, Throwable t) { logger.log(Level.SEVERE, "Thread exited with exception: " + thread.getName(), t); // Recovery or logging code } } } {code} Note that the uncaught exception handler is not called when the method {{ |
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.
Code Block | ||
---|---|---|
| ||
final class PoolService {
private final ExecutorService pool = Executors.newFixedThreadPool(10);
public void doSomething() {
Future<?> future = pool.submit(new Task());
// ...
try {
future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupted status
} catch (ExecutionException e) {
Throwable exception = e.getCause();
// Forward to exception reporter
}
}
}
|
Furthermore, any exception that prevents doSomething()
from obtaining the Future
value can be handled as required.
Exceptions
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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
TPS03-J | Low | Probable | Medium | P4 | L3 |
To-Do List
Tasklist | ||||
---|---|---|---|---|
| ||||
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name||
|
Related Guidelines
Bibliography
[API 2014] | Class ThreadFactory |
Chapter 7.3, "Handling Abnormal Thread Termination" |
...