What is AtomicLong in Java used for?

33.8k views Asked by At

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;
1

There are 1 answers

2
Makoto On BEST ANSWER

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.