Reference assignment is atomic so why use AtomicReference

前端 未结 3 920
闹比i
闹比i 2020-12-29 22:38

I have simple general question about AtomicReference.

Why use AtomicReference if reference assignment is atomic in java?

Also I would like to ask if referen

3条回答
  •  时光取名叫无心
    2020-12-29 22:52

    My previous answer was incorrect, as explained in the comment by juancn:

    That's the difference between Atomic* classes and volatile access. Reference assignment is atomic only in the sense that no word tearing can occur, but there's no visibility or reordering guarantees. Java guarantees atomic writes in this restricted sense for all primitive types and references but not for long/double (although in 64bit VMs I think they're always atomic).

    Previous answer

    It is necessary, mainly for compareAndSet and getAndSet methods. You cannot do this atomically otherwise (2 operations are needed).

提交回复
热议问题