开发者

java - Atomic access to field within object

If I need atomic 开发者_如何学Goaccess to an int field inside an object, is it sufficient to declare the field as an AtomicInteger or do I need to use an AtomicIntegerFieldUpdater? (and why?)


Using an AtomicInteger is sufficient. Atomic updaters are for use with volatile fields; the primary use case is data structures which have large numbers of fields that require atomic access; you use the field updater to use those fields with atomic semantics without having an AtomicInteger reference for each field.

For a detailed discussion, see this link.


AtomicInteger and friends should usually be sufficient, and is generally preferable as it does not involve reflection or other such hackery.

AtomicIntegerFieldUpdater can be useful where you have lots instances where the same needs to be updated, as this reduces the total number of objects. It's particularly useful if operations other than straight reading and writing are infrequent. For instance an AtomicReferenceFieldUpdater is used in java.nio for the attach method, which is generally set once (exposed as a get-and-set) and read many times.


In addition to biziclop's comment (see link):

Are java primitive ints atomic by design or by accident?

Just in case you've not came across this already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜