Look into classes like AtomicBoolean
and AtomicReference
. They're abstractions that do what you want, but aren't actually on the CPU.
One pattern I've used is for thread-safe state keeping.
private final AtomicBoolean isClosed = new AtomicBoolean(false);
...
public void close() {
if (this.isClosed.compareAndSet(false, true) {
....
}
}