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}
final 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 does not notify upper layers when it terminatedterminates unexpectedly because of the runtime exception. Moreover, there is no recovery code.
h2. Compliant Solution (Custom exception reporter)
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}
// ...
publicfinal class Task implements Runnable {
@Override public void run() {
try {
// ...
throw new NullPointerException();
// ...
} catch(Throwable t) {
// Execute any recovery code
MyExceptionReporter.report(t);
}
}
}
{code}
{mc} overriding the afterExecute method in ThreadPoolExecutor}} is also suggested {mc}
h2. Compliant Solution (Uncaught exception handler)
This compliant solution sets an uncaught exception handler for the thread pool. During the construction of the thread pool, a {{ThreadFactory}} argument 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}
final class PoolService {
private static final ThreadFactory factory = 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);
}
}
}
{code}
Note that the uncaught exception handler is not called whenif the method {{ExecutorService.submit()}} is used. This is because the thrown exception is considered to be part of the return status and consequently, it is rethrown by {{Future.get()}}, wrapped in an {{ExecutionException}} \[[Goetz 06|AA. Java References#Goetz 06]\].
h2. Risk Assessment
Failing to provide a mechanism to report that tasks in a thread pool failed as a result of an exceptional condition, can make it harder to find the problem, and may cause unresponsiveness.
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON37- J | low | probable | medium | {color:green}{*}P4{*}{color} | {color:green}{*}L3{*}{color} |
h3. Automated Detection
TODO
h3. Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON35-J].
h2. References
\[[API 06|AA. Java References#API 06]\] Class Thread, method {{stop}}, interface ExecutorService
\[[Goetz 06|AA. Java References#Goetz 06]\] Chapter 7: Cancellation and shutdown
----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|CON12-J. Avoid deadlock by requesting and releasing locks in the same order] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|VOID CON14-J. Ensure atomicity of 64-bit operations] |