Is this a correct way to stop Execution Task
- by Yan Cheng CHEOK
I came across code to stop execution's task.
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public void stop() {
executor.shutdownNow();
try {
executor.awaitTermination(100, TimeUnit.DAYS);
} catch (InterruptedException ex) {
log.error(null, ex);
}
}
public Runnable getRunnable() {
return new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// What if inside fun(), someone try to clear the interrupt flag?
// Say, through Thread.interrupted(). We will stuck in this loop
// forever.
fun();
}
}
};
}
I realize that, it is possible for Runnable to be in forever loop, as
Unknown fun may Thread.sleep, clear the interrupt flag and ignore the InterruptedException
Unknown fun may Thread.interrupted, clear the interrupt flag.
I was wondering, is the following way correct way to fix the code?
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private volatile boolean flag = true;
public void stop() {
flag = false;
executor.shutdownNow();
try {
executor.awaitTermination(100, TimeUnit.DAYS);
} catch (InterruptedException ex) {
log.error(null, ex);
}
}
public Runnable getRunnable() {
return new Runnable() {
public void run() {
while (flag && !Thread.currentThread().isInterrupted()) {
// What if inside fun(), someone try to clear the interrupt flag?
// Say, through Thread.interrupted(). We will stuck in this loop
// forever.
fun();
}
}
};
}