稍微修改自这里的内容:
import sun.misc.Unsafe;
import java.lang.reflect.*;
public class K {
private static Unsafe unsafe;
private static int fieldOffset;
private static K instance = new K();
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
fieldOffset = unsafe.fieldOffset(K.class.getDeclaredField("obj"));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private Object obj;
public synchronized static long toAddress(int o) {
instance.obj = o;
return unsafe.getLong(instance, fieldOffset);
}
public synchronized static Object toObject(long address) {
unsafe.putLong(instance, fieldOffset, address);
return instance.obj;
}
public static void main(String[] args) {
int x = 20;
System.err.println("x was = " + x);
long addr = toAddress(x);
System.err.println("&x = " + addr);
x = 70;
System.out.println("x is now " + x);
long newAddr = toAddress(x);
System.err.println("new (&x) = " + newAddr);
System.out.println("Previous value of x is " + toObject(addr)); // !!!
}
}
特别是,我担心标有!!!
的那行。如果原始的x
被垃圾回收了,那么它的地址可能就毫无价值了。
我的问题是,JVM会崩溃吗?还是toObject(BOGUS_VALUE)
总是会失败并抛出一个NullPointerException
(可以捕获)?
正如大多数人所知道的,Unsafe
文档的质量最好也只能算得上参差不齐。
K
中访问的是unsafe
,而不是这里的字段Unsafe
。 - Elliott Frisch