【问题标题】:java.lang.Integer object layout and it's overhead [duplicate]java.lang.Integer 对象布局及其开销[重复]
【发布时间】:2018-09-17 18:52:47
【问题描述】:

我使用了一个名为JOL (Java Object Layout) 的工具来尝试分析对象布局。它带有cli,我用它来分析java.lang.Integer。我看到 Integer 对象占用了 12 个额外的字节作为开销。该开销可以是对象所属类的地址的 4 个字节,另外 4 个用于垃圾收集,但是剩下的 4 个字节呢?我知道对象有一个整数 hashCode 值,但我不认为它是唯一的(即它不使用内存位置,而是使用原始值),因为:

Integer a = new Integer(12);
Integer b = new Integer(12);

System.out.println(a.hashCode() == 12 && b.hashCode() == 12);
// prints: true

日志:

$ java -jar jol-cli/target/jol-cli.jar internals java.lang.Integer
# WARNING: Unable to get Instrumentation. Dynamic Attach failed. You may add this JAR as -javaagent manually, or supply -Djdk.attach.allowAttachSelf
# Running 64-bit HotSpot VM.
# Using compressed oop with 0-bit shift.
# Using compressed klass with 0-bit shift.
# Objects are 8 bytes aligned.
# Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
# Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

Instantiated the sample instance via public java.lang.Integer(int)
 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           88 26 cf 22 (10001000 00100110 11001111 00100010) (584001160)
     12     4    int Integer.value                             0
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

【问题讨论】:

    标签: java jvm integer object-layout jol


    【解决方案1】:

    ...但是剩下的 4 个字节呢?

    缺少的 4 个字节将填充到下一个 8 字节边界。 Java 堆节点的大小是 8 字节的倍数。


    但是由于这是一个 64 位的 JVM,标记字是 8 个字节而不是 4 个字节,总共产生 12 个字节的头开销。

    【讨论】:

    • 有道理。谢谢。
    • 在这种情况下不是。 JOL 为填充槽打印“(填充)”,但这里使用了所有槽:8 字节标记字 + 4 字节 Klass 指针 + 4 字节值字段。
    • @apangin - 谢谢,已更正。
    猜你喜欢
    • 2019-07-19
    • 2015-06-14
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2014-07-17
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多