public class get_unsafe {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//利用反射获取对象theUnSafe
Field theUnsafe= Unsafe.class.getDeclaredField("theUnsafe");
//设置允许通过反射获取对象unsafe
theUnsafe.setAccessible(true);
//静态累,故类型未null
Unsafe unsafe=(Unsafe) theUnsafe.get(null);
System.out.println(unsafe);
Person person=new Person();
//获取对象域的偏移地址
long nameOffset=unsafe.objectFieldOffset(Person.class.getDeclaredField("name"));
long ageOffset=unsafe.objectFieldOffset(Person.class.getDeclaredField("age"));
//执行cas操作
unsafe.compareAndSwapInt(person,ageOffset,0,20);
unsafe.compareAndSwapObject(person,nameOffset,null,"李四");
System.out.println(person);
}
}
@Data
class Person{
volatile String name;
volatile int age;
}
Unsafe对象的相关操作
最新推荐文章于 2024-04-03 15:36:27 发布