JVM如何确保System.identityHashCode()永远不会改变? [英] How does the JVM ensure that System.identityHashCode() will never change?

查看:181
本文介绍了JVM如何确保System.identityHashCode()永远不会改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常 Object.hashCode() 的默认实现是内存中对象的已分配地址的某个函数(尽管这不是由 JLS 强制执行。鉴于VM在内存中分流对象,为什么 System.identityHashCode() 返回的值在对象的生命周期内永远不会改变?

Typically the default implementation of Object.hashCode() is some function of the allocated address of the object in memory (though this is not mandated by the JLS). Given that the VM shunts objects about in memory, why does the value returned by System.identityHashCode() never change during the object's lifetime?

如果是一次性计算(对象的 hashCode 计算一次并隐藏在对象标题中或那么这是否意味着两个对象可能具有相同的 identityHashCode (如果它们碰巧首先在内存中的同一地址分配)?

If it is a "one-shot" calculation (the object's hashCode is calculated once and stashed in the object header or something), then does that mean it is possible for two objects to have the same identityHashCode (if they happen to be first allocated at the same address in memory)?

推荐答案

现代JVM将值保存在对象标题中。我认为该值通常仅在首次使用时计算,以便将对象分配所花费的时间保持在最小值(有时低至十几个周期)。可以编译公共Sun JVM,以便所有对象的标识哈希码始终为1。

Modern JVMs save the value in the object header. I believe the value is typically calculated only on first use in order to keep time spent in object allocation to a minimum (sometimes down to as low as a dozen cycles). The common Sun JVM can be compiled so that the identity hash code is always 1 for all objects.

多个对象可以具有相同的标识哈希码。这就是哈希码的本质。

Multiple objects can have the same identity hash code. That is the nature of hash codes.

这篇关于JVM如何确保System.identityHashCode()永远不会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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