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.
Integers are object representations of literals and are therefore immutable, you can basically only read them. AtomicIntegers are containers for those values. You can read and set them. Same as asigning a value to variable.
An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
An atomic reference is ideal to use when you need to share and change the state of an immutable object between multiple threads. That is a super dense statement, so I will break it down a bit. First, an immutable object is an object that is effectively not changed after construction.
AtomicReference class provides operations on underlying object reference that can be read and written atomically, and also contains advanced atomic operations. AtomicReference supports atomic operations on underlying object reference variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With