Unsafe提供的主要功能有
- 内存操作(分配,释放)
- 定位、修改对象某字段的内存位置(包括私有的),使用CAS操作
- 挂起与恢复线程,park,unpark方法
- CAS操作
实例变量
public static final int ARRAY_CHAR_BASE_OFFSET; //char数组第一个变量
public static final int ARRAY_INT_BASE_OFFSET;
public static final int ARRAY_LONG_BASE_OFFSET;
public static final int ARRAY_FLOAT_BASE_OFFSET;
public static final int ARRAY_DOUBLE_BASE_OFFSET;
public static final int ARRAY_OBJECT_BASE_OFFSET;
public static final int ARRAY_BOOLEAN_INDEX_SCALE;
public static final int ARRAY_BYTE_INDEX_SCALE; //1
public static final int ARRAY_SHORT_INDEX_SCALE; //2
public static final int ARRAY_CHAR_INDEX_SCALE;
public static final int ARRAY_INT_INDEX_SCALE;
public static final int ARRAY_LONG_INDEX_SCALE;
public static final int ARRAY_FLOAT_INDEX_SCALE;
public static final int ARRAY_DOUBLE_INDEX_SCALE;
public static final int ARRAY_OBJECT_INDEX_SCALE;
public static final int ADDRESS_SIZE;
方法
数组操作
/**
获取数组第一个元素的偏移地址
**/
public native int arrayBaseOffset(Class arrayClass);
/*
获取数组中元素的增量地址
*/
public native int arrayIndexScale(Class arrayClass);
int baseOffset = unsafe.arrayBaseOffset(array.getClass());
int indexScale = unsafe.arrayIndexScale(array.getClass());
//元素内存地址 baseOffset + i*indexScale
//int indexScale为4, 4个字节
类型操作
//var2为对象var1的内存偏移量
public native int getInt(Object var1, long var2);
public native void putInt(Object var1, long var2, int var4);
分配、释放内存
public native long allocateMemory(long l);
public native long reallocateMemory(long l, long l1);
public native void freeMemory(long l);
挂起、恢复
public native void unpark(Object var1);
public native void park(boolean var1, long var2);
锁操作
/** @deprecated */
@Deprecated
public native void monitorEnter(Object var1);
/** @deprecated */
@Deprecated
public native void monitorExit(Object var1);
/** @deprecated */
@Deprecated
public native boolean tryMonitorEnter(Object var1);
其他
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
//先读出来才能做CAS
return var5;
}