簡介
最近在看dubbo源碼時(shí),經(jīng)巢娲瘢看到System.identityHashCode(obj) 的使用粘捎,想了解一下這個(gè)跟我們平常的hashcode方法又有啥異同薇缅,所以本篇簡單的探討一下攒磨。
概念
1、hashCode是 java.lang.Object.hashCode() 或者 java.lang.System.identityHashCode(obj) 會(huì)返回的值。他是一個(gè)對象的身份標(biāo)識(shí)泻骤。官方稱呼為:標(biāo)識(shí)哈希碼( identity hash code)。
2演痒、哪些特點(diǎn)?
(1)一個(gè)對象在其生命期中 identity hash code 必定保持不變趋惨;
(2)如果a == b器虾,那么他們的System.identityHashCode() 必須相等;
如果他們的System.identityHashCode() 不相等欧芽,那他們必定不是同一個(gè)對象(逆否命題與原命題真實(shí)性總是相同)葛圃;
(3)如果System.identityHashCode() 相等的話憎妙,并不能保證 a == b(畢竟這只是一個(gè)散列值厘唾,是允許沖突的)龙誊。
3、有什么作用载迄?
加速對象去重:由特征2可知护昧,只要判斷出兩個(gè)對象的hashCode不一致魂迄,就知道這兩個(gè)對象不是同一個(gè);又因?yàn)閔ashCode()的性能比 " == "性能高得多惋耙,所以多數(shù)時(shí)候捣炬,用它來判斷重復(fù)绽榛。
擴(kuò)展:為啥hashCode()性能高湿酸?
因?yàn)閔ashCode()的結(jié)果算出來后緩存起來灭美,下次調(diào)用直接用不需要重新計(jì)算推溃,提高性能
identityHashCode
看官方提供的API , 對System.identityHashCode()的解釋為 :
public static int identityHashCode([Object] x)
返回給定對象的哈希碼,該代碼與默認(rèn)的方法 hashCode() 返回的代碼一樣铁坎,無論給定對象的類是否重寫 hashCode()。null 引用的哈希碼為 0犁苏。
obj.hashcode()
hashCode()方法是頂級(jí)類Object類的提供的一個(gè)方法硬萍,所有的類都可以進(jìn)行對hashCode方法重寫。這時(shí)hash值計(jì)算根據(jù)重寫后的hashCode方法計(jì)算
異同
從上面的概念可以看出identityHashCode是根據(jù)Object類hashCode()方法來計(jì)算hash值围详,無論子類是否重寫了hashCode()方法朴乖。而obj.hashcode()是根據(jù)obj的hashcode()方法計(jì)算hash值
驗(yàn)證
@Test
public void testHashCode() {
TestExample example = new TestExample();
int exampleCode = System.identityHashCode(example);
int exampleCode2 = System.identityHashCode(example);
int exampleHashcode = example.hashCode();
System.out.println("example identityHashCode:" + exampleCode);
System.out.println("example2 identityHashCode:" + exampleCode2);
System.out.println("example Hashcode:" + exampleHashcode);
String str = "dd";
String str2 = "dd";
int strCode = System.identityHashCode(str);
int strHashCode = str.hashCode();
int str2HashCode = str.hashCode();
System.out.println("str identityHashCode:" + strCode);
System.out.println("str hashcode:" + strHashCode);
System.out.println("str2 hashcode:" + str2HashCode);
}
輸出:
example identityHashCode:1144748369
example2 identityHashCode:1144748369
example Hashcode:1144748369
str identityHashCode:340870931
str hashcode:3200
str2 hashcode:3200
結(jié)果分析:
(1)從上面樣例可以看出助赞,TestExample 對象沒重寫HashCode()方法,所以兩個(gè)都是調(diào)用Object的HashCode()方法哩都,自然結(jié)果一樣。
而String重寫了HashCode()方法咐汞,identityHashCode和HashCode結(jié)果自然不一樣化撕。
(2)str和str2的hashCode是相同的,是因?yàn)镾tring類重寫了hashCode方法约炎,它根據(jù)String的值來確定hashCode的值圾浅,所以只要值一樣,hashCode就會(huì)一樣狸捕。
hashCode如何計(jì)算的喷鸽?
JDK8 hashCode( )源碼:
進(jìn)入openjdk\jdk\src\share\classes\java\lang目錄下,可以看到 Object.java源碼
public native int hashCode();
即該方法是一個(gè)本地方法灸拍,Java將調(diào)用本地方法庫對此方法的實(shí)現(xiàn)做祝。由于Object類中有JNI方法調(diào)用,按照J(rèn)NI的規(guī)則鸡岗,應(yīng)當(dāng)生成JNI 的頭文件混槐,在此目錄下執(zhí)行javah -jni java.lang.Object 指令,將生成一個(gè)java_lang_Object.h頭文件轩性,
java_lang_Object.h頭文件關(guān)于hashcode方法的信息如下所示:
/*
* Class: java_lang_Object
* Method: hashCode
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_java_lang_Object_hashCode
(JNIEnv *, jobject);
1. Object對象的hashCode()方法在C語言文件Object.c中實(shí)現(xiàn)
打開openjdk\jdk\src\share\native\java\lang目錄声登,查看Object.c文件,可以看到hashCode()的方法被注冊成有JVM_IHashCode方法指針來處理:
/*-
* Implementation of class Object
*
* former threadruntime.c, Sun Sep 22 12:09:39 1991
*/
#include <stdio.h>
#include <signal.h>
#include <limits.h>
#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
//使用了上面生成的java_lang_Object.h文件
#include "java_lang_Object.h"
static JNINativeMethod methods[] = {
{"hashCode", "()I", (void *)&JVM_IHashCode},//hashcode的方法指針JVM_IHashCode
{"wait", "(J)V", (void *)&JVM_MonitorWait},
{"notify", "()V", (void *)&JVM_MonitorNotify},
{"notifyAll", "()V", (void *)&JVM_MonitorNotifyAll},
{"clone", "()Ljava/lang/Object;", (void *)&JVM_Clone},
};
2.JVM_IHashCode方法指針
在 openjdk\hotspot\src\share\vm\prims\jvm.cpp中定義揣苏,如下:
// java.lang.Object ///////////////////////////////////////////////
JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
JVMWrapper("JVM_IHashCode");
// as implemented in the classic virtual machine; return 0 if object is NULL
return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
JVM_END
如上可以看出悯嗓,JVM_IHashCode方法中調(diào)用了ObjectSynchronizer::FastHashCode方法
3. ObjectSynchronizer::fashHashCode方法的實(shí)現(xiàn):
ObjectSynchronizer::fashHashCode()方法在hotspot\src\share\vm\runtime\synchronizer.cpp
// hashCode() generation :
//
// 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:
//
//最終生成hash的方法
static inline intptr_t get_next_hash(Thread * Self, oop obj) {
intptr_t value = 0 ;
if (hashCode == 0) {
// This form uses an unguarded global Park-Miller RNG,
// so it's possible for two threads to race and generate the same RNG.
// On MP system we'll have lots of RW access to a global, so the
// mechanism induces lots of coherency traffic.
value = os::random() ;
} else
if (hashCode == 1) {
// This variation has the property of being stable (idempotent)
// between STW operations. This can be useful in some of the 1-0
// synchronization schemes.
intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3 ;
value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
} else
if (hashCode == 2) {
value = 1 ; // for sensitivity testing
} else
if (hashCode == 3) {
value = ++GVars.hcSequence ;
} else
if (hashCode == 4) {
value = cast_from_oop<intptr_t>(obj) ;
} else {
// 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.
unsigned t = Self->_hashStateX ;
t ^= (t << 11) ;
Self->_hashStateX = Self->_hashStateY ;
Self->_hashStateY = Self->_hashStateZ ;
Self->_hashStateZ = Self->_hashStateW ;
unsigned v = Self->_hashStateW ;
v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
Self->_hashStateW = v ;
value = v ;
}
value &= markOopDesc::hash_mask;
if (value == 0) value = 0xBAD ;
assert (value != markOopDesc::no_hash, "invariant") ;
TEVENT (hashCode: GENERATE) ;
return value;
}
//ObjectSynchronizer::FastHashCode方法的實(shí)現(xiàn),該方法最終會(huì)返回hashcode
intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
if (UseBiasedLocking) {
// NOTE: many places throughout the JVM do not expect a safepoint
// to be taken here, in particular most operations on perm gen
// objects. However, we only ever bias Java instances and all of
// the call sites of identity_hash that might revoke biases have
// been checked to make sure they can handle a safepoint. The
// added check of the bias pattern is to avoid useless calls to
// thread-local storage.
if (obj->mark()->has_bias_pattern()) {
// Box and unbox the raw reference just in case we cause a STW safepoint.
Handle hobj (Self, obj) ;
// Relaxing assertion for bug 6320749.
assert (Universe::verify_in_progress() ||
!SafepointSynchronize::is_at_safepoint(),
"biases should not be seen by VM thread here");
BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
obj = hobj() ;
assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
}
}
// hashCode() is a heap mutator ...
// Relaxing assertion for bug 6320749.
assert (Universe::verify_in_progress() ||
!SafepointSynchronize::is_at_safepoint(), "invariant") ;
assert (Universe::verify_in_progress() ||
Self->is_Java_thread() , "invariant") ;
assert (Universe::verify_in_progress() ||
((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
ObjectMonitor* monitor = NULL;
markOop temp, test;
intptr_t hash;
markOop mark = ReadStableMark (obj);
// object should remain ineligible for biased locking
assert (!mark->has_bias_pattern(), "invariant") ;
if (mark->is_neutral()) {
hash = mark->hash(); // this is a normal header
if (hash) { // if it has hash, just return it
return hash;
}
//調(diào)用get_next_hash生成hashcode
hash = get_next_hash(Self, obj); // allocate a new hash code
temp = mark->copy_set_hash(hash); // merge the hash code into header
// use (machine word version) atomic operation to install the hash
test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark);
if (test == mark) {
return hash;
}
// If atomic operation failed, we must inflate the header
// into heavy weight monitor. We could add more code here
// for fast path, but it does not worth the complexity.
} else if (mark->has_monitor()) {
monitor = mark->monitor();
temp = monitor->header();
assert (temp->is_neutral(), "invariant") ;
hash = temp->hash();
if (hash) {
return hash;
}
// Skip to the following code to reduce code size
} else if (Self->is_lock_owned((address)mark->locker())) {
temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
assert (temp->is_neutral(), "invariant") ;
hash = temp->hash(); // by current thread, check if the displaced
if (hash) { // header contains hash code
return hash;
}
// WARNING:
// The displaced header is strictly immutable.
// It can NOT be changed in ANY cases. So we have
// to inflate the header into heavyweight monitor
// even the current thread owns the lock. The reason
// is the BasicLock (stack slot) will be asynchronously
// read by other threads during the inflate() function.
// Any change to stack may not propagate to other threads
// correctly.
}
// Inflate the monitor to set hash code
monitor = ObjectSynchronizer::inflate(Self, obj);
// Load displaced header and check it has hash code
mark = monitor->header();
assert (mark->is_neutral(), "invariant") ;
hash = mark->hash();
if (hash == 0) {
hash = get_next_hash(Self, obj);
temp = mark->copy_set_hash(hash); // merge hash code into header
assert (temp->is_neutral(), "invariant") ;
test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark);
if (test != mark) {
// The only update to the header in the monitor (outside GC)
// is install the hash code. If someone add new usage of
// displaced header, please update this code
hash = test->hash();
assert (test->is_neutral(), "invariant") ;
assert (hash != 0, "Trivial unexpected object/monitor header usage.");
}
}
// We finally get the hash
return hash;
}
從上面代碼可以看出生成hash最終由get_next_hash函數(shù)生成舒岸,該函數(shù)提供了基于某個(gè)hashCode 變量值的六種方法。怎么生成最終值取決于hashCode這個(gè)變量值芦圾。
0 - 使用Park-Miller偽隨機(jī)數(shù)生成器(跟地址無關(guān))
1 - 使用地址與一個(gè)隨機(jī)數(shù)做異或(地址是輸入因素的一部分)
2 - 總是返回常量1作為所有對象的identity hash code(跟地址無關(guān))
3 - 使用全局的遞增數(shù)列(跟地址無關(guān))
4 - 使用對象地址的“當(dāng)前”地址來作為它的identity hash code(就是當(dāng)前地址)
5 - 使用線程局部狀態(tài)來實(shí)現(xiàn)Marsaglia's xor-shift隨機(jī)數(shù)生成(跟地址無關(guān))蛾派,從注釋中可以看到:這可能是最好的hashcode生成實(shí)現(xiàn)—在未來的版本中可能會(huì)將此設(shè)置為默認(rèn)值
擴(kuò)展補(bǔ)充:Xorshift 算法介紹
Xorshift 隨機(jī)數(shù)生成器是 George Marsaglia 發(fā)明的一類偽隨機(jī)數(shù)生成器。它們通過和自己邏輯移位后的數(shù)進(jìn)行異或操作來生成序列中的下一個(gè)數(shù)个少。這在現(xiàn)代計(jì)算機(jī)體系結(jié)構(gòu)非澈檎В快。它們是線性反饋移位寄存器的一個(gè)子類夜焦,其簡單的實(shí)現(xiàn)使它們速度更快且使用更少的空間壳澳。然而,必須仔細(xì)選擇合適參數(shù)以達(dá)到長周期茫经。
Xorshift生成器是非密碼安全的隨機(jī)數(shù)生成器中最快的一種巷波,只需要非常短的代碼和狀態(tài)萎津。雖然它們沒有進(jìn)一步改進(jìn)以通過統(tǒng)計(jì)檢驗(yàn),這個(gè)缺點(diǎn)非常著名且容易修改(Marsaglia 在原來的論文中指出)抹镊,用復(fù)合一個(gè)非線性函數(shù)的方式锉屈,可以得到比如像 xorshift+ 或 xorshift* 生成器。一個(gè)簡單的C語言實(shí)現(xiàn)的 xorshift+ 生成器通過了所有的 BigCrush 的測試(比 Mersenne Twister 算法和 WELL 算法的失敗次數(shù)減少了一個(gè)數(shù)量級(jí))垮耳,而且在 x86 上產(chǎn)生一個(gè)隨機(jī)數(shù)通常只需要不到十個(gè)時(shí)鐘周期颈渊,多虧了指令流水線。
VM到底用的是哪種方法终佛?
在openjdk\hotspot\src\share\vm\runtime\globals.hpp定義
JDK 8 和 JDK 9 默認(rèn)值:
product(intx, hashCode, 5,"(Unstable) select hashCode generation algorithm") ;
JDK 8 以前默認(rèn)值:
product(intx, hashCode, 0,"(Unstable) select hashCode generation algorithm") ;
不同的JDK俊嗽,生成方式不一樣。
注意:
雖然方式不一樣铃彰,但有個(gè)共同點(diǎn):java生成的hashCode和對象內(nèi)存地址沒什么關(guān)系绍豁。
修改生成方法
HotSpot提供了一個(gè)VM參數(shù)來讓用戶選擇identity hash code的生成方式:
-XX:hashCode
什么時(shí)候計(jì)算出來的
在VM里,Java對象會(huì)在首次真正使用到它的identity hash code(例如通過Object.hashCode() / System.identityHashCode())時(shí)調(diào)用VM里的函數(shù)來計(jì)算出值豌研,然后會(huì)保存在對象里妹田,后面對同一對象查詢其identity hash code時(shí)總是會(huì)返回最初記錄的值。
因此鹃共,不是對象創(chuàng)建時(shí)鬼佣。