首页 > 代码库 > JavaCAS深入理解(牛篇)

JavaCAS深入理解(牛篇)

鼠篇写的基本都是理论基础,最近在研究Unsafe的源码,大致看了看,还没有太深入这篇牛篇,只能算是做个资源记录吧。

从AtomicInteger类源码看起来。

AtomicInteger源码部分:

// setup to use Unsafe.compareAndSwapInt for updates    private static final Unsafe unsafe = Unsafe.getUnsafe();    private static final long valueOffset;    static {        try {            valueOffset = unsafe.objectFieldOffset                (AtomicInteger.class.getDeclaredField("value"));        } catch (Exception ex) { throw new Error(ex); }    }    private volatile int value;

这里比较神奇的是:unsafe.objectFieldOffset 这个方法,方法的参数是Field类型。这里就是声明的volatile类型的value属性。

跟踪到Hotspot源码里可以看到:

Unsafe.cpp

UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset(JNIEnv *env, jobject unsafe, jobject field))  UnsafeWrapper("Unsafe_ObjectFieldOffset");  return find_field_offset(field, 0, THREAD);UNSAFE_END
jint find_field_offset(jobject field, int must_be_static, TRAPS) {  if (field == NULL) {    THROW_0(vmSymbols::java_lang_NullPointerException());  }  oop reflected   = JNIHandles::resolve_non_null(field);  oop mirror      = java_lang_reflect_Field::clazz(reflected);  klassOop k      = java_lang_Class::as_klassOop(mirror);  int slot        = java_lang_reflect_Field::slot(reflected);  int modifiers   = java_lang_reflect_Field::modifiers(reflected);  if (must_be_static >= 0) {    int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);    if (must_be_static != really_is_static) {      THROW_0(vmSymbols::java_lang_IllegalArgumentException());    }  }  int offset = instanceKlass::cast(k)->offset_from_fields(slot);  return field_offset_from_byte_offset(offset);}

想看懂这段代码,必须看懂java在jvm里的对象体系了。

这篇文章很不错,对此做了一个大概况介绍  http://www.sczyh30.com/posts/Java/jvm-klass-oop/

JavaCAS深入理解(牛篇)