Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

...

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 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.

...

The task does not notify upper layers 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.

Compliant Solution (ThreadPoolExecutor hooks)

Wiki Markup
Task -specific recovery or clean-up actions can also be performed by overriding the {{afterExecute()}} hook of class {{java.util.concurrent.ThreadPoolExecutor}}'s {{afterExecute()}} hook..  This hook is called when a task completessuccessfully successfullyconcludes 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 recovery and clean-up actions
  }

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

Similarly, 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.

...