Search code examples
javaconcurrencyatomic

Why to use AtomicRefernce when reading & setting simple reference is already atomic operation


Could somebody please clarify my doubt on AtomicReferences. As par java memory model reading & writing references is always an atomic operation irrespective of 32 bit or 64 bit machine. So in what scenario using AtomicRefernce will be useful.


Solution

  • There are other operations provided by AtomicReference that you can't implement with normal references.

    For instance to make sure which value your are replacing:

    ref.compareAndSet(expectedCurrentValue, newValue);
    

    To get the last value and replace with something else:

    oldValue = ref.getAndSet(newValue);
    

    With AtomicReference you can do those operations safely even when multiple threads are trying to access the same references.