java.lang.Object的hashCode使用的算法究竟是什么

djh*_*987 6 java openjdk

JVM实现java.lang.Object隐式hashCode()方法时使用的算法是什么?

[ OpenJDK或者Oracle JDK在答案中是首选].

Mic*_*rry 5

它依赖于实现(并且非常重要,算法完全取决于实现,只要它是一致的.)但是,根据这里的答案,您可以看到在OpenJDK 7中生成哈希的本机源文件(查看的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
//
Run Code Online (Sandbox Code Playgroud)

如前所述,默认算法只是简单地使用随机数,但是进一步说明一个有趣的评论:

// 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.
Run Code Online (Sandbox Code Playgroud)

这类似于(obj ^ stwRandom)上面列出的可能性中提到的方法,但它通过将"特定于线程的状态"信息绑定到散列中来解决与连续快速分配的对象相关的不需要的规则 - 所以如果恰好分配了两个对象在非常相似的时间由于它们被分配在同时执行的两个单独的线程上,馈送到散列中的离散线程信息应该仍然确保将产生离散的足够的散列.