我的理解:声明一个变量volatile可以保证其他线程对该变量的写入可见性。本质上,每个writevolatile 变量都发生在后续reads.
我了解它的原子性AtomicBoolean.compareAndSet()以及它如何提供不提供的read+write操作的原子性volatile。但我没有看到任何文档通过以下方式提供可见性保证AtomicBoolean:
- 每个成功
write的 byAtomicBoolean.compareAndSet()最终都会对后续线程AtomicBoolean.get()和AtomicBoolean.compareAndSet()其他线程可见。
但是,我一直看到标记为thread-safe这样的代码,
// 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
}
}
}
变量不应该executing也声明volatile吗private static volatile AtomicBoolean executing = new AtomicBoolean(false);?那么所需要的可见性保证AtomicBoolean就实现了吗?