64 位 VM 上 Java 中的对象标头大小,内存小于 4GB [英] Object header size in Java on 64bit VM with <4GB RAM

查看:29
本文介绍了64 位 VM 上 Java 中的对象标头大小,内存小于 4GB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果 JVM 的可用 RAM 是 4GB,是否有办法让 64 位 VM 使用 8 字节对象头而不是 12 字节对象头.

I wanted to know if there is some way to have the 64bit VM use 8byte object headers instead of 12byte object headers if the usable RAM for the JVM is 4GB anyway.

或者在Linux上是这样,如果不是在Windows上?有人可以用这段代码测试一下吗?

Or is it like that on Linux, if not on windows? Could someone test this with this code?

import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class ObjectSizes {
    String s1;
    String s2;
    public static void main(String[] args) throws Exception {
        Unsafe unsafe;
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe)field.get(null);
        } catch (Exception ex) {
            throw new RuntimeException("Can't get Unsafe instance.", ex);
        }
        Field s1Field = ObjectSizes.class.getDeclaredField("s1");
        Field s2Field = ObjectSizes.class.getDeclaredField("s2");
        long s1OffSet = unsafe.objectFieldOffset(s1Field);
        long s2OffSet = unsafe.objectFieldOffset(s2Field);
        System.out.println("We are running "+System.getProperty("java.version"));
        System.out.println("Object header size is "+s1OffSet+" bytes.");
        System.out.println("Object reference size is "+(s2OffSet-s1OffSet)+" bytes.");
    }
}

推荐答案

在 64 位 JVM 上似乎不可能有 8 字节的对象标头.标头由一个标记词"、一个指向对象类的指针、在数组情况下的数组大小以及到达下一个 8 字节边界的填充组成.

It doesn't look like it's possible to have an 8-byte object header on a 64-bit JVM. The header consists of a "mark word", a pointer to the object's class, array size in case of an array, and padding to reach the next 8-byte boundary.

  ,------------------+------------------+------------------ +---------------.
  |    mark word     |   klass pointer  |  array size (opt) |    padding    |
  `------------------+------------------+-------------------+---------------'

  • 标记字可用于存储本机指针实现锁并帮助 GC,因此它在 64 位 JVM 上占用 8 个字节.
  • 对于小于 32GB 的堆,指向对象类的指针被压缩为 4 个字节.
  • 填充可用于存储字段之一.
    • The mark word may be used to store native pointers to implement locks and to help GC, so it occupies 8 bytes on a 64-bit JVM.
    • With heaps smaller than 32GB the pointer to the object's class is compressed to 4 bytes.
    • The padding may be used to store one of the fields.
    • 因此,64 位系统上的对象头可以占用 8 + 4 = 12 个字节,但不会更少.

      Therefore the object header on a 64-bit system can occupy as little as 8 + 4 = 12 bytes, but not less.

      这篇关于64 位 VM 上 Java 中的对象标头大小,内存小于 4GB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆