My understanding: Declaring a variable volatile
guarantees the visibility for other threads about writes to that variable. Essentially, every write
to volatile variable happens-before subsequent reads
.
I understand the atomicity of AtomicBoolean.compareAndSet()
and how it provides the atomicity of read+write
operation that volatile
doesn't. But I don't see any doc providing visibility guarantee by AtomicBoolean
like the following:
- Every successful
write
byAtomicBoolean.compareAndSet()
will eventually be visible to subsequentAtomicBoolean.get()
andAtomicBoolean.compareAndSet()
by other threads.
But, I keep seeing code labelled as thread-safe
which are like this,
// default false so that first-thread that execute() can enter the logic block
private static final AtomicBoolean executing = new AtomicBoolean(false);
public void execute() {
if (executing.compareAndSet(false, true)) { // check if the executing is previously false and if so update it to true
try {
// thead-safe code, i.e only one thread guaranteed to execute at any point of time time
} finally {
executing.set(false); // executing thread now re-sets the test value
}
}
}
Shouldn't the variable executing
also declared volatile
, like private static volatile AtomicBoolean executing = new AtomicBoolean(false);
? So the visibility guarantee needed by AtomicBoolean
is achieved?