A small question about memory visibility.
CodeSample1:
class CustomLock {
private boolean locked = false;
public boolean lock() {
if(!locked) {
locked = true;
return true;
}
return false;
}
}
This code is prone to errors in a multi-threaded environment, first because of an "if-then-act", which is not atomic, and the second because of potential memory visibility problems, where, for example, threadA sets the field to true, but threadB, which later wants to read the value of the field, may not see it and still see the value false.
The easiest solution is to use a synchronized keyword, as in CodeSample2.
CodeSample2:
class CustomLock {
private boolean locked = false;
public synchronized boolean lock() {
if(!locked) {
locked = true;
return true;
}
return false;
}
}
Now, if I want to use an atomic variable, and for example, AtomicBoolean (the question applies to all atomic variables),
CodeSample3:
public static class CustomLock {
private AtomicBoolean locked = new AtomicBoolean(false);
public boolean lock() {
return locked.compareAndSet(false, true);
}
}
, "if-then-act" CodeSample1, AtomicBoolean.
, , , 2 lock() CodeSample3 , , , AtomicBoolean ?
, , , , ...