查看java对象占用内存大小

mac2024-10-13  49

引入maven依赖:

<dependency> <groupId>org.openjdk.jol</groupId> <artifactId>jol-core</artifactId> <version>0.9</version> </dependency>

用org.openjdk.jol.info.ClassLayout的方法输出对象占用大小信息:

package com.pilaf.classlayout; import lombok.Data; /** * @description: * @author: pilaf * @create: 2019-10-31 21:17 */ @Data public class MyTest { private int a; private boolean b; } package com.pilaf.classlayout; import org.openjdk.jol.info.ClassLayout; /** * @description: * @author: pilaf * @create: 2019-10-31 21:17 */ public class LayoutDemo { public static void main(String[] args) { MyTest myTest = new MyTest(); System.out.println("myTest:"+myTest); System.out.println(ClassLayout.parseInstance(myTest).toPrintable()); } }

输出的内容如下:

myTest:MyTest(a=0, b=false) # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope com.pilaf.classlayout.MyTest 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) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253) 12 4 int MyTest.a 0 16 1 boolean MyTest.b false 17 7 (loss due to the next object alignment) Instance size: 24 bytes Space losses: 0 bytes internal + 7 bytes external = 7 bytes total

因为jvm要求对象所占的内存空间大小是8字节的整数倍,这个对象本来占17字节,为了对齐,补上了7字节,一共占24字节(8字节*3)。

最新回复(0)