【发布时间】:2014-10-09 13:14:39
【问题描述】:
这是在 Java 6 内存模型之后。在 32 位 JVM 中,对象的 Shallow 大小为
8 bytes (object header) + total of all instance variables + padding (optional)
如果前 2 个项加起来不是 8 的倍数,则会有填充。
在 64 位 JVM 中,Shallow 大小为
16 bytes (object header) + total of all instance variables + padding (optional)
我的理解是这个Object header由2个词组成(oracle热点VM)
- 一个经典词
- 一个标记词
在 32 位 JVM 上,对象标头 = 2 * 32 位 = 64 位 = 8 个字节
在 64 位 JVM 上,对象头 = 2 * 64 位 = 128 位 = 16 字节
但是使用 CompressedOops,3 个低位被截断,因此对于小于 32 gigs 的堆,在 64 位 JVM 上它应该回到 8 个字节
但是当我使用 JOL(Java 对象布局)测试对象布局时,它显示了 12 个字节的对象头。
测试代码
public class App {
public static void main( String[] args )
{
System.out.println(System.getProperty("java.version"));
System.out.println(VMSupport.vmDetails());
System.out.println(ClassLayout.parseClass(A.class).toPrintable());
}
}
class A {
int a;
}
输出
1.8.0_05
Running 64-bit HotSpot VM.
Using compressed references with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
com.layout.test.jolTesting.A object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header) N/A
12 4 int A.a N/A
Instance size: 16 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
我在这里缺少什么会增加额外的 4 个字节?
【问题讨论】:
-
你在使用 HotSpot 吗?
-
是 Oracle 热点 JDK 8 虚拟机。我现在在我的问题中添加了输出和代码
标签: java memory-layout objectsize