javamultithreadingatomicreference

Does AtomicReference.compareAndSet(old,new) guarantees old.field wasn't change?


Does AtomicReference.compareAndSet(old,new) guarantee

  1. old.field wasn't change?
  2. Or it just guarantees old wasn't reassign to a new object?

if 2 is true, does it mean AtomicReference is useful only with immutable objects like String? (Because in case of mutability of old the old.field changes are lost with a successfully compareAndSet)


Solution

  • AtomicReference only checks reference equality, and does not check for changes to fields.

    As a result, it is primarily only useful with immutable types.