0. Preface
The unsafe class can provide us with an efficient and thread-safe way to manipulate variables, dealing directly with memory data.
1. How to obtain unsafe entities
private static Unsafe getUnsafeInstance() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeInstance.setAccessible(true); return (Unsafe) theUnsafeInstance.get(Unsafe.class);}
This method can get an object's property relative to the object's offset in memory, so that we can find this property in the object memory based on that offset.
long objectOffset = unsafe.objectFieldOffset(User.class.getDeclaredField("value"));Object value = unsafe.getObject(new User(), objectOffset);
//获取静态字段的偏移量unsafe.staticFieldOffset(User.class.getDeclaredField("value"));
2. Common Methods Introduction 2.1 compareandswapint (thread-safe)
/*** 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。* * @param obj 需要更新的对象* @param offset obj中整型field的偏移量* @param expect 希望field中存在的值* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值* @return 如果field的值被更改返回true*/ public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);
2.2 Compareandswapobject is the same as the above method function, but is a variable of type Object
public native boolean compareAndSwapObject(Object obj, long offset, Object expect, Object update);
2.3 Putorderedint Set the value and write to main memory immediately, the variable must be of type volatile
/*** 设置 volatile 类型到int值* * @param obj 需要更新的对象* @param offset obj中整型field的偏移量* @param expect 希望field中存在的值*/void sun.misc.Unsafe.putOrderedInt(Object obj, long offset, int expect)
Reference:
Https://www.cnblogs.com/daxin/p/3366606.html
Java Non-open source unsafe class