Java volatile reference vs. AtomicReference

后端 未结 6 1077
慢半拍i
慢半拍i 2020-11-28 02:06

Is there any difference between a volatile Object reference and AtomicReference in case I would just use get() and set()-

6条回答
  •  执念已碎
    2020-11-28 02:57

    JDK source code is one of the best ways to answers confusions like this. If you look at the code in AtomicReference, it uses a volatie variable for object storage.

    private volatile V value;
    

    So, obviously if you are going to just use get() and set() on AtomicReference it is like using a volatile variable. But as other readers commented, AtomicReference provides additional CAS semantics. So, first decide if you want CAS semantics or not, and if you do only then use AtomicReference.

提交回复
热议问题