JVM
中用于实现java.lang.Object
隐式hashCode()
方法的算法是什么?答案偏向于使用OpenJDK
或Oracle JDK
。JVM
中用于实现java.lang.Object
隐式hashCode()
方法的算法是什么?答案偏向于使用OpenJDK
或Oracle JDK
。get_next_hash()
函数),该版本实际上指定了许多可能的算法。// Possibilities:
// * MD5Digest of {obj,stwRandom}
// * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
// * A DES- or AES-style SBox[] mechanism
// * One of the Phi-based schemes, such as:
// 2654435761 = 2^32 * Phi (golden ratio)
// HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
// * A variation of Marsaglia's shift-xor RNG scheme.
// * (obj ^ stwRandom) is appealing, but can result
// in undesirable regularity in the hashCode values of adjacent objects
// (objects allocated back-to-back, in particular). This could potentially
// result in hashtable collisions and reduced hashtable efficiency.
// There are simple ways to "diffuse" the middle address bits over the
// generated hashCode values
//
如前所述, 默认算法是使用随机数,但是下面有一个有趣的评论提到:
// Marsaglia's xor-shift scheme with thread-specific state
// This is probably the best overall implementation -- we'll
// likely make this the default in future releases.
这类似于上述可能性列表中提到的(obj ^ stwRandom)
方法,但它通过将“线程特定状态”信息绑定到哈希中来避免了与快速连续分配对象相关的不必要规律性 - 因此,如果由于在两个并行执行的线程上分配了两个非常相似的时间而分配了两个对象,则馈入哈希的离散线程信息应确保生成足够离散的哈希。