I don´t get the difference between these two:
AtomicReference<Integer> atomicReference = new AtomicReference<>(1);
vs.
AtomicInteger atomicInteger = new AtomicInteger(1);
Can someone generally say when to use AtomicReference? Hope someone can help me. Thanks.
A very important difference is that the methods compareAndSet
and weakCompareAndSet
have different semantics for AtomicReference<Integer>
than they do for AtomicInteger
. This is because with AtomicReference<Integer>
, those methods use ==
for comparing and two Integer
objects can be equal without being ==
. With AtomicInteger
, the comparison is of the integer value equality, not reference identity.
As others have pointed out, AtomicInteger
has additional features not available with AtomicReference<Integer>
. Also, AtomicInteger
extends Number
, so it inherits all the Number
methods (doubleValue()
, etc.) and can be used whenever a Number
is expected.