Unsafe
Unsafe
获取
public class UnSafeT {
public static void main(String[] args) throws Exception {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");//获取theUnsafe字段
theUnsafe.setAccessible(true);//暴力访问
Unsafe unsafe = (Unsafe) theUnsafe.get(null);//获取unSafe对象
System.out.println(unsafe);//sun.misc.Unsafe@4b67cf4d
}
}
CAS
public class UnSafeT {
public static void main(String[] args) throws Exception {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");//获取theUnsafe字段
theUnsafe.setAccessible(true);//暴力访问
Unsafe unsafe = (Unsafe) theUnsafe.get(null);//获取unSafe对象
//计算偏移量
long offId = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
long offName = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));
Student student = new Student();
/**compareAndSwapInt(Object obj, long offSet, int pre, int cur);
*@Param obj:操作的对象,offSet:字段偏移量,pre:原始值,cur:要修改后的值
*@Return void
**/
unsafe.compareAndSwapInt(student,offId,0,2);
unsafe.compareAndSwapObject(student,offName,null,"coder");
System.out.println(student);//UnSafeT.Student(id=2, name=coder)
}
@Data
static class Student{
private volatile int id;
private volatile String name;
}
}
AtomicInteger的实现原理
public class UnSafeT {
private static Unsafe unsafe;
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");获取theUnsafe字段
theUnsafe.setAccessible(true);//暴力访问
unsafe = (Unsafe) theUnsafe.get(null);//获取unSafe对象
} catch (Exception e) {
e.printStackTrace();
}
}
static class AtomicInteger {
private volatile int value;
private static long offValue;
static {
//计算偏移量
try {
offValue = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
//get
public int get() {
return value;
}
//cas
public boolean compareAndSet(int pre, int cur) {
return unsafe.compareAndSwapInt(this, offValue, pre, cur);
}
}
}
get
public class UnSafeT {
private static Unsafe unsafe;
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");获取theUnsafe字段
theUnsafe.setAccessible(true);//暴力访问
unsafe = (Unsafe) theUnsafe.get(null);//获取unSafe对象
} catch (Exception e) {
e.printStackTrace();
}
}
@Data
static class Student{
private volatile int value;
private volatile String name;
}
public static void main(String[] args) throws NoSuchFieldException {
Student student = new Student();
long offValue = unsafe.objectFieldOffset(Student.class.getDeclaredField("value"));
long offName = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));
unsafe.compareAndSwapInt(student,offValue,0,56);
unsafe.compareAndSwapObject(student,offName,null,"coder");
int value = unsafe.getInt(student, offValue);//获取整形值
Object name = unsafe.getObject(student, offName);//获取引用类型值
System.out.println(value);//56
System.out.println(name);//coder
System.out.println(student);//UnSafeT.Student(value=56, name=coder)
}
}