Java对象的内存布局:对象头(Header)、实例数据(Instance Data)和对齐填充(Padding)。无论是32位还是64位的HotSpot,使用的都是8字节对齐。也就是说每个java对象,占用的字节数都是8的整数倍。(对象头 + 实例数据 + padding) % 8等于0且0 <= padding < 8。在网上看到各种介绍如何手动计算对象大小的文章,总结了几点:
1.基本数据类型占用的字节数,JVM规范中有明确的规定,无论是在32位还是64位的虚拟机,占用的内存大小是相同的。
2.reference类型在32位JVM下占用4个字节,但是在64位下可能占用4个字节或8个字节,这取决于是否启用了64位JVM的指针压缩参数UseCompressedOops。
3.对象头占用8字节
4.开启(-XX:+UseCompressedOops)指针压缩,对象头占12字节; 关闭(-XX:-UseCompressedOops)指针压缩,对象头占16字节。
5.64位JVM上,数组对象的对象头占用24个字节,启用压缩之后占用16个字节。之所以比普通对象占用内存多是因为需要额外的空间存储数组的长度。
6.对象内存布局中的实例数据,不包括类的static字段的大小,因为static字段是属于类的,被该类的所有对象共享。
public class PmDataRecord { private long beginTime; private String poId; private long neIdLong; public PmDataRecord(long beginTime, String poId, long neIdLong) { this.beginTime = beginTime; this.poId = poId; this.neIdLong = neIdLong; } }
import org.openjdk.jol.info.ClassLayout; import org.openjdk.jol.info.GraphLayout; public class Test { static void print(String message) { System.out.println(message); System.out.println("-------------------------"); } public static void main(String[] args) { PmDataRecord obj = new PmDataRecord(111111111111111L, "12345", 111111111111L); print(ClassLayout.parseInstance(obj).toPrintable()); //查看对象外部信息 print(GraphLayout.parseInstance(obj).toPrintable()); //获取对象总大小 print("size : " + GraphLayout.parseInstance(obj).totalSize()); } }
打印结果
PmDataRecord object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 09 00 00 00 (00001001 00000000 00000000 00000000) (9)
4 4 (object header) 58 27 64 14 (01011000 00100111 01100100 00010100) (342107992)
8 8 long PmDataRecord.beginTime 111111111111111
16 8 long PmDataRecord.neIdLong 111111111111
24 4 java.lang.String PmDataRecord.poId (object)
28 4 (loss due to the next object alignment)
Instance size: 32 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
-------------------------
PmDataRecord@4bae78d object externals:
ADDRESS SIZE TYPE PATH VALUE
42f2c48 32 PmDataRecord (object)
42f2c68 14640 (something else) (somewhere else) (something else)
42f6598 16 java.lang.String .poId (object)
42f65a8 158768 (something else) (somewhere else) (something else)
431d1d8 24 [C .poId.value [1, 2, 3, 4, 5]
-------------------------
size : 72
-------------------------
引包:
jol-core-0.9.jar
包地址:
http://central.maven.org/maven2/org/openjdk/jol/jol-core/0.9/