简体   繁体   English

java - 原子访问 object 中的字段

[英]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?如果我需要对 object 中的 int 字段进行原子访问,是否足以将该字段声明为 AtomicInteger 还是需要使用 AtomicIntegerFieldUpdater? (and why?) (为什么?)

Using an AtomicInteger is sufficient.使用AtomicInteger就足够了。 Atomic updaters are for use with volatile fields;原子更新器用于volatile字段; 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.您可以使用字段更新程序来使用具有原子语义的字段,而无需为每个字段提供AtomicInteger引用。

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. AtomicInteger和朋友通常就足够了,并且通常更可取,因为它不涉及反射或其他此类黑客行为。

AtomicIntegerFieldUpdater can be useful where you have lots instances where the same needs to be updated, as this reduces the total number of objects. AtomicIntegerFieldUpdater在您有很多需要更新的实例时很有用,因为这会减少对象的总数。 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.例如, AtomicReferenceFieldUpdaterjava.nio中用于 attach 方法,通常设置一次(公开为 get-and-set)并读取多次。

In addition to biziclop's comment (see link):除了 biziclop 的评论(见链接):

Are java primitive ints atomic by design or by accident? java 原始整数是设计的还是偶然的?

Just in case you've not came across this already.以防万一你还没有遇到过这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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