...
A finally
block can be used to perform clean-up actions. If the task cannot be refactored, it may be wrapped within a Runnable
or Callable
that catches Throwable
, and submitted to the thread pool.
Compliant Solution (ThreadPoolExecutor
hooks)
Wiki Markup |
---|
Task specific recovery or clean-up actions can also be performed by overriding the class {{java.util.concurrent.ThreadPoolExecutor}}'s {{afterExecute()}} hook. This hook is called when a task completes successfully 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 | ||
---|---|---|
| ||
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);
// Perform task-specific recovery and clean-up
}
@Override
public void terminated() {
super.terminated();
// Perform final clean-up
}
}
|
...