简体   繁体   English

关于java.util.concurrent AtomicInteger

[英]About java.util.concurrent AtomicInteger

I came across source code of AtomicInteger class on GrepCode and found following code snippet. 我在GrepCode遇到了AtomicInteger类的源代码,并发现了以下代码片段。

   static {
   try {
       valueOffset = unsafe.objectFieldOffset
       (AtomicInteger.class.getDeclaredField("value"));
    } catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;

How the static block know the offset of instance variable value . 静态块如何知道实例变量值的偏移量。 Static initialise when class is loaded and linked . 加载和链接类时的静态初始化。 so how can we know about the offset of the instance value at class loading time . 所以我们怎么知道类加载时实例值的偏移量。 Object are created after class loaded . 在类加载后创建对象。 Is that "value" instance variable will have fixed offset when ever object is created. 创建对象时,“值”实例变量是否具有固定的偏移量? Please explain . 请解释 。

Unsafe.objectFieldOffset() gets the offset of the declared field in the class. Unsafe.objectFieldOffset()获取类中已声明字段的偏移量。 This is class-level information. 这是类级别的信息。 It has nothing to do with the instance values of that field. 它与该字段的实例值无关。

The offset is just used to determine which memory location to address when updating the value field of AtomicInteger instances. 偏移量仅用于确定更新AtomicInteger实例的value字段时要寻址的内存位置。

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

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