Last active
May 17, 2019 02:52
-
-
Save zhoulifu/3359c9d5017468404c93d61e0b05b6bc to your computer and use it in GitHub Desktop.
two-phrase termination pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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