Is this as safe as using an AtomicReference?
private volatile String myMember;
public void setMyMember(String s) {
myMember = s;
}
vs.
private final AtomicReference<String> myMember = new AtomicReference<>();
public void setMyMember(String s) {
while (true) {
String current = myMember.get();
if (myMember.compareAndSet(current, s))
break;
}
}
Your code is “safe” but doesn’t do the same thing as the
AtomicReferencecode. Typically, theAtomicReferenceloop withcompareAndSetis used when someone is trying to add something to a list or object and they want to protect against the race conditions with multiple threads.For example:
In your case, since you are using a simple
Stringobject, just making itvolatilewill be fine. There is no point in doing thecompareAndSet. If you still want to useAtomicReference, then just callmyMember.set(...).