2014-07-23 29 views
5

中有什麼JVM用於實現java.lang.Object的隱hashCode()方法的算法?恰恰是通過什麼java.lang.Object中的的hashCode所使用的算法

[OpenJDKOracle JDK中的答案是優選的]。

+2

只是好奇...因爲Java是一個開源的,什麼阻止你看自己? –

+5

@ PM77-1可能事實上,這是「本地」方法,並不是很多人知道在哪裏尋找它的實現。 – Pshemo

+2

請參閱http://stackoverflow.com/questions/17977495/java-object-hashcode-algorithm - 該鏈接指向本地源代碼。然而,在閱讀源文件後,我更加困惑。 – user2864740

回答

5

這是實現相關的(和大量這樣的算法是完全到執行,只要它是一致的。)然而,正如每答案here,你可以看到在OpenJDK的生成散列native source file 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 
// 

如前所述,默認算法是簡單地用一個隨機數去,但一個有趣的評論進一步down狀態:

// 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)方法,但它通過捆綁「特定線程狀態」信息到散也得到周圍連續快速分配對象有關的不良規律 - 所以,如果由於兩個對象在同時執行的兩個獨立線程上分配,因此兩個對象恰巧在非常相似的時間分配,散列的散列線程信息仍應確保生成足夠多的散列哈希。

相關問題