简体   繁体   中英

About java.util.concurrent AtomicInteger

I came across source code of AtomicInteger class on GrepCode and found following code snippet.

   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. 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.

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