我们以64位虚拟机讲解

首先我们简单说下Java对象的内存布局

说明
1.类型指针默认占用8个字节,如果开启了UseCompressedClassPointers,类型指针占用4个字节
2.如果对象是数组,则对象头中存在对象长度,否则不存在
执行命令
$ java -XX:+PrintCommandLineFlags -version
输出如下

说明开启了UseCompressedClassPointers,则类型指针占用4字节
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
测试代码
Integer obj = new Integer(19);
System.out.println(ClassLayout.parseInstance(obj).toPrintable());
输出

一个Integer(19)占用16字节
我们设置-XX:-UseCompressedOops -XX:-UseCompressedClassPointers. 不启用压缩,再次执行上面的代码

一个Integer(19)占用24字节
读者朋友,当面试官问你new Object()在内存中占用多少字节? 你会了吗?
网友评论