Versions Compared

Key

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

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 JVMJava Virtual Machine, or simply log the details of the failure.

...

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
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();
    // ...
  }
}

...

Compliant Solution (ThreadPoolExecutor Hooks)

Wiki MarkupTask-specific recovery or clean-up 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|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6450211] for more information \[[SDN 2008|AA. Bibliography#SDN 08]\]). When using this approach, substitute the executor service with a custom {{ThreadPoolExecutor}} that overrides the {{afterExecute()}} hook as shown below (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
bgColor#ccccff

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, Throwable t) {
    super.afterExecute(r, t);
    if (t != null) {
      // Exception occurred, forward to handler
    }
    // ... Perform task-specific clean-upcleanup actions
  }

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

...

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
bgColor#ccccff

final class PoolService {
  private static final ThreadFactory factory =
 new
     new ExceptionThreadFactory(new MyExceptionHandler());
  private static final ExecutorService pool =
      Executors.newFixedThreadPool(10, factory);

  public void doSomething() {
    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 {
    // ...

    @Override public void uncaughtException(Thread thread, Throwable t) {
      // Recovery or logging code
    }
  }
}

Wiki MarkupThe {{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 will 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 re-thrown by {{ and rethrown by Future.get()}} \ [[Goetz 2006|AA. Bibliography#Goetz 06]\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 re-throw rethrow the exception so that it can be handled locally.

Code Block
bgColor#ccccff

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.

...

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

TPS03-J

low Low

probable Probable

medium Medium

P4

L3

To-Do List

Tasklist
To-Do
To-Do
 
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name|| 

Related Guidelines

MITRE CWE

CWE ID -392, " Missing Report of Error Condition"

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="64a76b88-0399-42c2-9042-fc5799b4a492"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

interfaces ExecutorService, ThreadFactory and class Thread

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="759c4df2-4b32-475b-b371-fc44484d91bf"><ac:plain-text-body><![CDATA[

[[Goetz 2006

API 2014]

Class Thread
Interface ExecutorService

Interface ThreadFactory

[Goetz 2006aAA. Bibliography#Goetz 06]]

Chapter 7.3: Handling abnormal thread termination

]]></ac:plain-text-body></ac:structured-macro>

, "Handling Abnormal Thread Termination"

 

...

Image Added Image Added Image Removed      10. Thread Pools (TPS)