What is AtomicLong in Java used for?

2020-05-24 20:19发布

问题:

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 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.