Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is AtomicLong in Java used for?

Can some one explain what AtomicLong is used for? For example, what's the difference in the below statements?

private Long transactionId; private AtomicLong transactionId; 
like image 776
Nilotpal Avatar asked Feb 22 '16 06:02

Nilotpal


People also ask

How do you initialize AtomicLong in Java?

If you want to create an AtomicLong with an initial value, you can do so like this: AtomicLong atomicLong = new AtomicLong(123); This example passes a value of 123 as parameter to the AtomicLong contructor, which sets the initial value of the AtomicLong instance to 123 .

Is AtomicLong thread-safe?

Yes it is. And AtomicLong is too. Not only is it thread-safe, but in fact its thread-safety is the only reason to use it (as opposed to a plain int ).

What are atomic classes in Java?

Java provides atomic classes such as AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Objects of these classes represent the atomic variable of int, long, boolean, and object reference respectively. These classes contain the following methods.


1 Answers

There are significant differences between these two objects, although the net result is the same, they are definitely very different and used under very different circumstances.

You use a basic Long object when:

  • You need the wrapper class
  • You are working with a collection
  • You only want to deal with objects and not primitives (which kinda works out)

You use an AtomicLong when:

  • You have to guarantee that the value can be used in a concurrent environment
  • You don't need the wrapper class (as this class will not autobox)

Long by itself doesn't allow for thread interopability since two threads could both see and update the same value, but with an AtomicLong, there are pretty decent guarantees around the value that multiple threads will see.

Effectively, unless you ever bother working with threads, you won't need to use AtomicLong.

like image 75
Makoto Avatar answered Oct 05 '22 06:10

Makoto