Skip to content

Instantly share code, notes, and snippets.

@zhoulifu
Last active May 17, 2019 02:52
Show Gist options
  • Save zhoulifu/3359c9d5017468404c93d61e0b05b6bc to your computer and use it in GitHub Desktop.
Save zhoulifu/3359c9d5017468404c93d61e0b05b6bc to your computer and use it in GitHub Desktop.
two-phrase termination pattern
public abstract class TerminableThread extends Thread {
private volatile boolean stopRequested;
private volatile boolean stopped;
public boolean isStopRequested() {
return stopRequested;
}
public boolean isStopped() {
return stopped;
}
public void terminate() {
if (stopRequested) {
return ;
}
stopRequested = true;
try {
beforeTermination();
} finally {
if (isIdle()) {
super.interrupt();
}
}
}
@Override
public void interrupt() {
terminate();
}
@Override
public void run() {
Throwable t = null;
try {
for (;;) {
if (isStopRequested() && isIdle()) {
break;
}
doRun();
}
} catch (Throwable cause) {
t = cause;
} finally {
afterTermination(t);
}
stopped = true;
}
protected void beforeTermination(){
// NOOP
}
protected void afterTermination(Throwable t){
// NOOP
}
protected abstract void doRun() throws Exception;
protected abstract boolean isIdle();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment