gpt4 book ai didi

java - 在Java中, "new Object()"在堆栈和堆上分配了多少内存

转载 作者:行者123 更新时间:2023-12-02 08:41:09 24 4
gpt4 key购买 nike

这是我的面试问题之一,但我仍在努力解决它。如果我创建“new Object()”,对此对象的引用将位于堆栈上,在 64 位上将是 8 个字节。然后,问题是堆上有什么。面试官后来提到,堆上总会分配两个东西,一个是“Class”对象,另一个是“Monitor”。有人可以解释一下创建“new Object()”时分配了多少内存/什么吗?

最佳答案

If I create "new Object()", the reference to this object will be on the stack, which will be 8 bytes on 64 bit.

即使对于 64 位 JVM,它也很可能是 4 个字节。 Oracle/OpenJDK 支持 CompressesOops,它使用 4 个字节作为引用。

Then, the question was what's on heap.

对象的 header 。它没有字段。

The interviewer later mentioned that two things will always be allocated on heap, which are "Class" object

Class 对象是堆外存储信息的代理。即使类的实例存在,它也不必存在(尽管对于 Object 来说它可能已经存在了)

as well as "Monitor".

同样,只有在使用时才会创建监视器,即同步

Can someone please explain a bit more about how much memory/what is allocated when "new Object()" gets created?

在 64 位 JVM 上, header 默认为 12 字节,但是通过对象对齐,它将使用 16 字节。在 32 位 JVM 上,它只有 8 个字节。

在 32 位 JVM 和带有 CompressedOops 的 64 位 JVM 上,引用只有 4 个字节(这是大多数 JVM 的情况)

关于java - 在Java中, "new Object()"在堆栈和堆上分配了多少内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52436675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com