Skip to content

Instantly share code, notes, and snippets.

@nschlimm
Created April 4, 2012 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nschlimm/2301734 to your computer and use it in GitHub Desktop.
Save nschlimm/2301734 to your computer and use it in GitHub Desktop.
DefensiveThreadPoolExecutor
private class DefensiveThreadPoolExecutor extends ThreadPoolExecutor {
public DefensiveThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
LinkedBlockingQueue<Runnable> workQueue, ThreadFactory factory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory, handler);
}
/**
* "Last" task issues a signal that queue is empty after task processing was completed.
*/
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (state == PREPARE) {
closeLock.lock(); // only one thread will pass when closer thread is awaiting signal
try {
if (getQueue().isEmpty() && state < SHUTDOWN) {
System.out.println("Issueing signal that queue is empty ...");
isEmpty.signal();
state = SHUTDOWN; // -> no other thread can issue empty-signal
}
} finally {
closeLock.unlock();
}
}
super.afterExecute(r, t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment