我想知道如果 JVM 的可用 RAM 仍然是 4GB,是否有某种方法可以让 64 位 VM 使用 8 字节对象头而不是 12 字节对象头。
或者如果不是在 Windows 上,在 Linux 上也是这样吗?有人可以用这段代码测试吗?
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class ObjectSizes {
String s1;
String s2;
public static void main(String[] args) throws Exception {
Unsafe unsafe;
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
} catch (Exception ex) {
throw new RuntimeException("Can't get Unsafe instance.", ex);
}
Field s1Field = ObjectSizes.class.getDeclaredField("s1");
Field s2Field = ObjectSizes.class.getDeclaredField("s2");
long s1OffSet = unsafe.objectFieldOffset(s1Field);
long s2OffSet = unsafe.objectFieldOffset(s2Field);
System.out.println("We are running "+System.getProperty("java.version"));
System.out.println("Object header size is "+s1OffSet+" bytes.");
System.out.println("Object reference size is "+(s2OffSet-s1OffSet)+" bytes.");
}
}