简体   繁体   中英

java - Atomic access to field within object

If I need atomic access 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM