本文介绍了对象的地址在其生命周期中是否固定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象的地址在其生命周期中是不变的还是可以改变?我只是觉得一个对象的地址永远不会改变。它是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).

这是因为通常在eden空间中分配对象。然后他们移动到幸存者空间,如果他们在一些垃圾收集周期中幸存下来,那么他们也会移动到老一代空间。所以它确实改变了。但是如果对象是在伊甸园空间中分配的,并且通过停留在同一空间中而收集垃圾,那么地址也不会改变。类似地,如果对象太大而无法在eden空间中分配,那么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.

希望有所帮助。

编辑

回答以下问题:

hashCodes 由JVM保存在对象头中。所以它是不变的。在创建对象时,默认情况下会将其分配给 1 ,但是当您第一次使用该对象时,它会被计算出来并存储在标题中。它永远不会在对象的整个生命周期中发生变化。

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.

这篇关于对象的地址在其生命周期中是否固定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:18