I often use the following pattern to create a cancellable thread:
public class CounterLoop implements Runnable {
private volatile AtomicBoolean cancelPending = new AtomicBoolean(false);
@Override
public void run() {
while (!cancelPending.get()) {
//count
}
}
public void cancel() {
cancelPending.set(true);
}
}
But I’m not sure that cancelPending MUST be a AtomicBoolean. Can we just use a normal boolean in this case?
Using both
volatileandAtomicBooleanis unnecessary. If you declare thecancelPendingvariable asfinalas follows:the JLS semantics for
finalfields mean that synchronization (orvolatile) will not be needed. All threads will see the correct value for thecancelPendingreference. JLS 17.5 states:… but there are no such guarantees for normal fields; i.e. not
finaland notvolatile.You could also just declare
cancelPendingas avolatile boolean… since you don’t appear to be using the test-and-set capability ofAtomicBoolean.However, if you used a non-volatile
booleanyou would need to usesynchronizedto ensure that all threads see an up-to-date copy of thecancelPendingflag.