Java volatile reference vs. AtomicReference

后端 未结 6 1076
慢半拍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 03:07

    There are several differences and tradeoffs:

    1. Using an AtomicReference get/set has the same JMM semantics as a volatile field(as the javadoc states), but the AtomicReference is a wrapper around a reference, so any access to the field involves a further pointer chase.

    2. The memory footprint is multiplied (assuming a compressed OOPs environment, which is true for most VMs):

      • volatile ref = 4b
      • AtomicReference = 4b + 16b (12b object header + 4b ref field)
    3. AtomicReference offers a richer API than a volatile reference. You can regain the API for the volatile reference by using an AtomicFieldUpdater, or with Java 9 a VarHandle. You can also reach straight for sun.misc.Unsafe if you like running with scissors. AtomicReference itself is implemented using Unsafe.

    So, when is it good to choose one over the other:

    • Only need get/set? Stick with a volatile field, simplest solution and lowest overhead.
    • Need the extra functionality? If this is a performance(speed/memory overhead) sensitive part of your code make a choice between AtomicReference/AtomicFieldUpdater/Unsafe where you tend to pay in readability and risk for your performance gain. If this not a sensitive area just go for AtomicReference. Library writers typically use a mix of these methods depending on targeted JDKs, expected API restrictions, memory constraints and so on.

提交回复
热议问题