对象的地址在其生命周期内是否固定?

2022-01-16 00:00:00 object memory jvm java memory-address

对象的地址在其生命周期内是不变的还是可以改变的?我只是认为一个对象的地址永远不会改变.它依赖于JVM吗?我还没有找到任何明确的规范.

Is the address of an object constant during its life cycle or can it change? I just thought address of an object never changes. Is it JVM dependent? I Haven't found any clear spec.

推荐答案

java中对象的地址不固定;相反,它可能会改变(视情况而定).

The address of an object in java is not fixed; rather, it may change (subjected to conditions).

这是因为通常对象是在伊甸园空间中分配的.然后它们移动到幸存者空间,如果它们在一些垃圾收集周期中幸存下来,它们也会移动到老年代空间.所以它确实改变了.但是,如果对象被分配在伊甸园空间中,并且通过留在同一空间中进行垃圾收集,则地址不会改变.类似地,如果对象太大而无法在伊甸园空间分配,那么 JVM 会在老年代分配对象,如果它通过留在分配的位置被垃圾收集,那么地址也不会改变.

This is because normally objects are allocated in eden space. Then they move to survivor space, then also to the old generation space if they survived some garbage collection cycles. So it does change. But if the object is allocated in eden space and also garbage collected by staying in the same space, then the address will not change. Similarly if the object is too large to be allocated in eden space, then the JVM allocates the object in the old generation and if it is garbage collected by staying where it was allocated, then also address does not change.

还有一点你应该知道,即使一个对象停留在一代,如果是停留在同一代进行垃圾回收,地址可能会发生变化,因为它可能在进行垃圾回收时被垃圾回收器移动了,例如从伊甸园空间到幸存者,幸存者到幸存者,甚至在压缩的情况下进入老年代.

One more thing you should know that even if one object stays in a generation, if it is garbage collected by staying in the same generation, the address may change, because it may have moved by the garbage collector while doing garbage collection, e.g. from eden space to survivor, survivor to survivor or even into the old generation in the event of compacting.

从以上条件可以看出,地址的移动是依赖于JVM的.

From the above conditions it is clear that the moving of an address is JVM dependent.

希望对你有帮助.

编辑

回答以下问题:

如果我创建一个新对象并将其存储在地图中,它就存储在其中基于 hashCode(使用对象的内存生成根据java的位置).现在对象的地址发生了变化(导致在不同的 hashCode 中),因此根据答案,代码永远不能从地图中获取对象??

if I create a new Object and store it in a map, where it is stored based on hashCode (which is generated using the object's memory location as per java). Now the address of the object changed(resulting in a different hashCode), so as per the answer, the code can never fetch the object from the map??

hashCodes被JVM保存在对象头中.所以它是恒定的.在创建 object 时,它默认分配给 1 但是当您第一次使用该对象时,它会被计算并存储在标题中.它在 Object 的整个生命周期内都不会改变.

hashCodes are saved in the object header by JVM. So it is constant. While creating an object it is assigned to 1 by default but when you use the object for the first time it gets calculated and gets stored in the header. It never changes throughout the life of the Object.

相关文章