import sun.misc.Unsafe;
/**
* @author woniu
* @date 2022/6/3 12:07
**/
public class Test {
private static final Unsafe unsafe = Unsafe.getUnsafe();
private String head;
private static final long headOffset;
static {
try {
headOffset = unsafe.objectFieldOffset
(TestCAS.class.getDeclaredField("head"));
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
System.out.println(headOffset);
}
}
会有如下异常:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.SecurityException: Unsafe
at sun.misc.Unsafe.getUnsafe(Unsafe.java:90)
那正确的方式是:
import sun.misc.Unsafe;
import java.lang.reflect.Field;
/**
* @author woniu
* @date 2022/6/3 11:46
**/
public class TestCAS {
private static final Unsafe unsafe;
private static final long headOffset;
private transient volatile String head;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
headOffset = unsafe.objectFieldOffset
(TestCAS.class.getDeclaredField("head"));
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
System.out.println(headOffset);
}
}