Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What´s the difference between AtomicReference<Integer> vs. AtomicInteger?

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.

like image 911
GedankenNebel Avatar asked Apr 21 '13 19:04

GedankenNebel


People also ask

What is difference between AtomicInteger and Integer?

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.

What is AtomicInteger?

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.

When should I use AtomicReference?

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.

What is an AtomicReference?

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.


Video Answer


1 Answers

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.

like image 99
Ted Hopp Avatar answered Sep 21 '22 18:09

Ted Hopp