因此,显然,如果只在 AtomicReference 上使用 get ()和 set () ,就像使用 Volatile变量一样。但是正如其他读者所评论的,AtomicReference 提供了额外的 CAS 语义。因此,首先决定是否需要 CAS 语义,如果需要,则使用 AtomicReference。
private volatile Status status;
...
public setNewStatus(Status newStatus){
status = newStatus;
}
public void doSomethingConditionally() {
if(status.isOk()){
System.out.println("Status is ok: " + status); // here status might not be OK anymore because in the meantime some called setNewStatus(). setNewStatus should be synchronized
}
}
使用 AtomicReference 的实现将免费提供一个即写即拷的同步。
private AtomicReference<Status> statusWrapper;
...
public void doSomethingConditionally() {
Status status = statusWrapper.get();
if(status.isOk()){
System.out.println("Status is ok: " + status); // here even if in the meantime some called setNewStatus() we're still referring to the old one
}
}