What is AtomicLong in Java used for?

丶灬走出姿态 提交于 2019-12-03 10:34:36

问题


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.



来源:https://stackoverflow.com/questions/35546956/what-is-atomiclong-in-java-used-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!