As pointed out by others, AtomicReference<Integer>
uses == to compare objects. Therefore,compareAndSet(expect, update)
will update your initial reference only if expect
equals to the object stored in your your atomic reference using ==.
It can lead to some tricky bugs if you use AtomicReference
for numeric types, i.e. Integer
or Long
. Please note that static constructors of those classes (for example, Integer.valueOf(int value)
) return internally cached objects for small values. In other words, two different calls to Integer.valueOf(5)
returns the same instance of Integer
. It is safe, as the classes are immutable. In the result, if you use AtomicReference<Integer>
whereas you should really be using AtomicInteger
, it may work fine for these small numbers, because == may actually compare the same objects. It gets worse only when you begin to handle with higher values at some point.
Summing up, using AtomicInteger
is much safer for numeric operations :)
new Integer(3)
will obviously not have the same identity though. This can cause all sorts of surprising behaviours. – Barbbarba