[TOC]
1.对象内存布局
详见
大致分成三部分,对象头,实例数据,对齐填充
对象所占内存=对象头+实例数据(+对齐填充)
1.1 对象头
由mark word和类型指针组成
markword占8个字节,类型指针占4个字节(开启指针压缩,默认开启,可以通过虚拟机参数设置-XX:-UseCompressedOops关闭)
1.2 实例数据
八大基本类型根据所占字节来计算(例如int 4字节),包装类型占4字节
1.3 对齐填充
如果对象头+实例数据的所占字节,不能被8整除,就自动填充
2.测试
引入依赖
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
2.1 空对象大小
public class EmptyObj {
// 空对象 没有属性的对象
public static void main(String[] args) {
EmptyObj obj = new EmptyObj();
System.out.println(ClassLayout.parseInstance(obj).toPrintable());
}
}
打印结果
空对象所占内存大小=16B,看到最后一行offset为12,自动填充了4B
cn.summit.jvm.EmptyObj object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 05 c1 00 f8 (00000101 11000001 00000000 11111000) (-134168315)
12 4 (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
设置压缩指针关闭
VM optional = -XX:-UseCompressedOops
cn.summit.jvm.EmptyObj object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 28 30 f8 1b (00101000 00110000 11111000 00011011) (469250088)
12 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
Instance size: 16 bytes
2.2 其它对象
public class ClazzObj {
int a = 4;
int b = 4;
int c = 4;
// int f = 4;
// LocalDateTime a = LocalDateTime.now();
// String str;
// 8 + 4 + 4+ 4 = 20 + 4
// 关闭 8 + 8+ 4*3 = 28 + 4
public static void main(String[] args) {
// 8 + 4 +16 = 28 +4 =32
ClazzObj obj = new ClazzObj();
System.out.println(ClassLayout.parseInstance(obj).toPrintable());
}
}
大小计算 8+4+4*3=24 %8=0,所以大小为24b
验证
cn.summit.jvm.ClazzObj object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 05 c1 00 f8 (00000101 11000001 00000000 11111000) (-134168315)
12 4 int ClazzObj.a 4
16 4 int ClazzObj.b 4
20 4 int ClazzObj.c 4
Instance size: 24 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
网友评论