Java 查看对象布局工具 - Java Object Layout

chan 作者
阅读 13388 喜欢 1

引入依赖

<!-- https://mvnrepository.com/artifact/org.openjdk.jol/jol-core -->
<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.10</version>
</dependency>

使用方式

/**
 * 测试 User 对象在内存中的布局
 * 
 * @author CHAN
 * @date 2020/04/28
 */
public class JolTest {
    public static void main(String[] args) {
        User user = new User();
        String s = ClassLayout.parseInstance(user).toPrintable();
        System.out.println(s);
    }

    static class User {
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

对象的状态

输出结果如下:可以看出对象占用内存 20 字节,但是因为 JVM 虚拟机是 64 位,所以大小必须是 8 字节的倍数,于是对象被填充为 24 字节。

com.zqskate.blogs.web.ui.service.test.JolTest$User 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 User.age                                  0
     16     4   java.lang.String User.name                                 null
     20     4                    (loss due to the next object alignment)
Instance size: 24 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

对象的五种状态:无锁状态、偏向锁、轻量锁、重量锁、GC标记

全部评论0