1、java Obeject類中的hashcode函數
/**
返回一個對象的散列碼,這個方法有利於哈希表,例如HashMap
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
*/
public native int hashCode();
2、hashcode方法和equals 方法都是Obeject類中的方法,當不重寫equals 方法時,比較的是 兩個對象是否完全相等。
public boolean equals(Object obj) {
return (this == obj);
}
我們知道hashcode方法和equals 方法是配套使用的,當我們重寫equals 方法時我們需要重寫hashcode方法。爲什麼?因爲java中有這樣的規範。規範如下
摘自Object規範 (JavaSE6):
- 在應用程序的執行期間,只要對象的equals方法的比較操作所用到的信息沒有被修改,那麼對這同一個對象調用多次,hashCode方法都必須始終如一地返回同一個整數。在同一個程序多次執行過程中,每次執行所返回的整數可以不一致;
- 如果兩個對象根據equals方法比較是相等的,那麼調用者兩個對象的hashCode方法必須返回同一個整數;
- 如果兩個對象根據equals方法比較是不相等的,那麼調用者兩個對象的hashCode方法不一定返回不同整數。給不相等的對象產生截然不同的整數結果,有可能提高散列表(hash table)的性能;
3、tostring方法也與hashcode方法有關,不重寫時返回的是hashcode的16進製表達形式
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
4、hashcode是本地方法,具體實現是用c++寫的,我們可以下載openjdk源碼閱讀。
下載地址:https://download.csdn.net/download/u014520797/12454866
5、用c++版本的eclipse來看看 源碼
聲明在synchronizer.hpp 實現在這裏synchronizer.cpp。
主要函數有兩個get_next_hash和FastHashCode,FastHashCode函數裏會調用get_next_hash函數,get_next_hash函數中有6種產生hashcode的方式,由於hashCode默認值是5(可在虛擬機啓動時配置 -XX:hashCode, java8以前默認值是0,java8以後是5),所以默認是最後一種產生方式。
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) {//這與第5個方式類似,都調用了cast_from_oop函數,只不過此處又增加了位偏移和addrBits ^ (addrBits >> 5) ^ GVars.stwRandom計算
// 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 異或-位移方案
// 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;
}
簡單點:
0 - 使用Park-Miller僞隨機數生成器(跟地址無關)
1 - 使用地址與一個隨機數做異或(地址是輸入因素的一部分)
2 - 總是返回常量1作爲所有對象的identity hash code(跟地址無關)
3 - 使用全局的遞增序列(跟地址無關)
4 - 使用對象地址的“當前”地址來作爲它的identity hash code(就是當前地址)
5 - 使用線程局部狀態來實現Marsaglia's 異或-位移隨機數生成(跟地址無關)
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;
}
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;
}
6、Marsaglia's 異或-位移方案是什麼?https://www.docin.com/p-1787859407.html
弗羅裏達州立大學一位叫做喬治.馬爾薩莉亞(George Marsaglia)的數學家發表了一篇使用位移以及亦或運算生成隨機數的方法。
7、總結:常規情況下,hashcode與地址無關。
解讀c++源碼請看這裏https://www.zhihu.com/question/29976202
參考資料:https://www.docin.com/p-1787859407.html
https://zhuanlan.zhihu.com/p/28270828
https://blog.csdn.net/weixin_30566111/article/details/97126305
http://www.voidcn.com/search/nsepkc
https://zhuanlan.zhihu.com/p/33915892