Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Tasks that run for extended periods of time Long-running tasks should provide a notification mechanism to alert upper layers when they terminate abnormallynotify the application upon abnormal termination. Failure to do this so 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 the application level is to use an exception handler. The handler can perform diagnostic actions, clean-up and shutdown the Java Virtual Machine (JVM) or simply log the details of the failure. 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. Nonetheless, it is usually a good practice to install a task-specific or global exception handler to initiate recovery, or log the exceptional condition.

Noncompliant Code Example (Abnormal task termination)

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

Code Block
bgColor#FFCCCC
final class PoolService {
  private final ExecutorService pool = Executors.newFixedThreadPool(10);
		  
  public void doSomething() {	   
    pool.execute(new Task());
  }	
}

final class Task implements Runnable {
  @Override public void run() {
    // ...
    throw new NullPointerException();
    // ...	
  }
}

The task does not notify upper layers the application when it terminates unexpectedly as a result of the runtime exception. Moreover, it does not use any recovery mechanism. Consequently, if any Task throws a NullPointerException, the exception is ignored.

...

Wiki Markup
Task-specific recovery or clean-up actions can also be performed by overriding the {{afterExecute()}} hook of class {{java.util.concurrent.ThreadPoolExecutor}}.  This hook is called when a task successfully concludes by executing all statements in its {{run()}} method, or halts because of an exception (A {{java.lang.Error}} might not be captured on specific implementations, see [Bug ID 6450211|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6450211] \[[SDN 08|AA. Java References#SDN 08]\]).  When using this approach, substitute the executor service with a custom {{ThreadPoolExecutor}} that overrides the {{afterExecute()}} hook as shown below:

Code Block
bgColor#ccccff
final class PoolService {
  // The values have been hardcoded for brevity
  ExecutorService pool = new CustomThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, 
                         new ArrayBlockingQueue<Runnable>(10));
  // ...
}

class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  // ... Constructor ...

  @Override
  public void afterExecute(Runnable r, Throwable t) {
    super.afterExecute(r, t);
    if (t != null) {
      // Exception occurred, forward to handler
    }
    // ... Perform task-specific clean-up actions
  }

  @Override
  public void terminated() {
    super.terminated();
    // ... Perform final clean-up actions
  }
}

Similarly, the 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 over its lifetime, much like a finally block.

Compliant Solution (Uncaught

...

Exception Handler)

This compliant solution sets an uncaught exception handler on behalf of the thread pool. An argument of type ThreadFactory is passed to the thread pool while constructing itduring construction. The factory is responsible for creating new threads and setting the uncaught exception handler on their behalf. The Task class Task remains the same as the is unchanged from the noncompliant code example.

...

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

Exceptions

CON32-EX1: 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. Nonetheless, it is usually a good practice to install a task-specific or global exception handler to initiate recovery or log the exceptional condition.

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 source of the issue.

...