3 hashCode的內幕 tips:面試常問/常用/常出錯 hashCode到底是什麼?是不是對象的記憶體地址? 1) 直接用記憶體地址? 目標:通過一個Demo驗證這個hasCode到底是不是記憶體地址 public native int hashCode(); com.hashcode.HashCo ...
3 hashCode的內幕
tips:面試常問/常用/常出錯
hashCode到底是什麼?是不是對象的記憶體地址?
1) 直接用記憶體地址?
目標:通過一個Demo驗證這個hasCode到底是不是記憶體地址
public native int hashCode();
com.hashcode.HashCodeTest
package com.hashcode;
import org.openjdk.jol.vm.VM;
import java.util.ArrayList;
import java.util.List;
public class HashCodeTest {
//目標:只要發生重覆,說明hashcode不是記憶體地址,但還需要證明(JVM代碼證明)
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
int num = 0;
for (int i = 0; i < 150000; i++) {
//創建新的對象
Object object = new Object();
if (integerList.contains(object.hashCode())) {
num++;//發生重覆(記憶體地址肯定不會重覆)
} else {
integerList.add(object.hashCode());//沒有重覆
}
}
System.out.println(num + "個hashcode發生重覆");
System.out.println("List合計大小" + integerList.size() + "個");
}
}
15萬個迴圈,發生了重覆,說明hashCode不是記憶體地址(嚴格的說,肯定不是直接取的記憶體地址)
思考一下,為什麼不能直接用記憶體地址呢?
- 提示:jvm垃圾收集演算法,對象遷移……
那麼它到底是什麼?如何生成的呢
2) 不是地址那在哪裡?
既然不是記憶體地址,那一定在某個地方存著,那在哪裡存著呢?
答案:在對象頭裡!(畫圖。類在jvm記憶體中的佈局)
對象頭分為兩部分,一部分是上面指向class描述的地址Klass,另一部分就是Markword
而我們這裡要找的hashcode在Markword里!(標記位意義,不用記!)
32位:
64位:
3) 什麼時候生成的?
new的瞬間就有hashcode了嗎??
show me the code!我們用代碼驗證
package com.hashcode;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
public class ShowHashCode {
public static void main(String[] args) {
ShowHashCode a = new ShowHashCode();
//jvm的信息
System.out.println(VM.current().details());
System.out.println("-------------------------");
//調用之前列印a對象的頭信息
//以表格的形式列印對象佈局
System.out.println(ClassLayout.parseInstance(a).toPrintable());
System.out.println("-------------------------");
//調用後再列印a對象的hashcode值
System.out.println(Integer.toHexString(a.hashCode()));
System.out.println(ClassLayout.parseInstance(a).toPrintable());
System.out.println("-------------------------");
//有線程加重量級鎖的時候,再來看對象頭
new Thread(()->{
try {
synchronized (a){
Thread.sleep(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println(Integer.toHexString(a.hashCode()));
System.out.println(ClassLayout.parseInstance(a).toPrintable());
}
}
結果分析
結論:在你沒有調用的時候,這個值是空的,當第一次調用hashCode方法時,會生成,加鎖以後,不知道去哪裡了……
4) 怎麼生成的?
接上文 , 我們追究一下,它詳細的生成及移動過程。
我們都知道,這貨是個本地方法
public native int hashCode();
那就需要藉助上面提到的辦法,通過JVM虛擬機源碼,查看hashcode的生成
1)先從Object.c開始找hashCode映射
src\share\native\java\lang\Object.c
JNIEXPORT void JNICALL//jni調用
//全路徑:java_lang_Object_registerNatives是java對應的包下方法
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
//jni環境調用;下麵的參數methods對應的java方法
(*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0]));
}
JAVA--------------------->C++函數對應
//JAVA方法(返回值)----->C++函數對象
static JNINativeMethod methods[] = {
//JAVA方法 返回值 (參數) c++函數
{"hashCode", "()I", (void *)&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},
};
JVM_IHashCod在哪裡呢?
2)全局檢索JVM_IHashCode
完全搜不到這個方法名,只有這個還湊合有點像,那這是個啥呢?
src\share\vm\prims\jvm.cpp
/*
JVM_ENTRY is a preprocessor macro that
adds some boilerplate code that is common for all functions of HotSpot JVM API.
This API is a connection layer between the native code of JDK class library and the JVM.
JVM_ENTRY是一個預載入巨集,增加一些樣板代碼到jvm的所有function中
這個api是位於本地方法與jdk之間的一個連接層。
所以,此處才是生成hashCode的邏輯!
*/
JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
JVMWrapper("JVM_IHashCode");
//調用了ObjectSynchronizer對象的FastHashCode
return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
JVM_END
3)繼續,ObjectSynchronizer::FastHashCode
先說生成流程,留個印象:
intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
//是否開啟了偏向鎖(Biased:偏向,傾向)
if (UseBiasedLocking) {
//如果當前對象處於偏向鎖狀態
if (obj->mark()->has_bias_pattern()) {
Handle hobj (Self, obj) ;
assert (Universe::verify_in_progress() ||
!SafepointSynchronize::is_at_safepoint(),
"biases should not be seen by VM thread here");
//那麼就撤銷偏向鎖(達到無鎖狀態,revoke:廢除)
BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
obj = hobj() ;
//斷言下,看看是否撤銷成功(撤銷後為無鎖狀態)
assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
}
}
// ……
ObjectMonitor* monitor = NULL;
markOop temp, test;
intptr_t hash;
//讀出一個穩定的mark;防止對象obj處於膨脹狀態;
//如果正在膨脹,就等他膨脹完畢再讀出來
markOop mark = ReadStableMark (obj);
//是否撤銷了偏向鎖(也就是無鎖狀態)(neutral:中立,不偏不斜的)
if (mark->is_neutral()) {
//從mark頭上取hash值
hash = mark->hash();
//如果有,直接返回這個hashcode(xor)
if (hash) { // if it has hash, just return it
return hash;
}
//如果沒有就新生成一個(get_next_hash)
hash = get_next_hash(Self, obj); // allocate a new hash code
//生成後,原子性設置,將hash放在對象頭裡去,這樣下次就可以直接取了
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.
//如果已經升級成了重量級鎖,那麼找到它的monitor
//也就是我們所說的內置鎖(objectMonitor),這是c里的數據類型
//因為鎖升級後,mark里的bit位已經不再存儲hashcode,而是指向monitor的地址
//而升級的markword呢?被移到了c的monitor里
} else if (mark->has_monitor()) {
//沿著monitor找header,也就是對象頭
monitor = mark->monitor();
temp = monitor->header();
assert (temp->is_neutral(), "invariant") ;
//找到header後取hash返回
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())) {
//輕量級鎖的話,也是從java對象頭移到了c里,叫helper
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;
}
}
......略
問:
為什麼要先撤銷偏向鎖到無鎖狀態,再來生成hashcode呢?這跟鎖有什麼關係?
答:
mark word里,hashcode存儲的位元組位置被偏向鎖給占了!偏向鎖存儲了鎖持有者的線程id
(參考上面的markword圖)
擴展:關於hashCode的生成演算法(瞭解)
// hashCode() generation :
// 涉及到c++演算法領域,感興趣的同學自行研究
// 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:
//
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 ; // 返回1
} else if (hashCode == 3) {
value = ++GVars.hcSequence ;//返回一個Sequence序列號
} 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.
//馬薩利亞教授寫的xor-shift 隨機數演算法(異或隨機演算法)
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 ;
}
5)總結
通過分析虛擬機源碼我們證明瞭hashCode不是直接用的記憶體地址,而是採取一定的演算法來生成
hashcode值的存儲在mark word里,與鎖共用一段bit位,這就造成了跟鎖狀態相關性
- 如果是偏向鎖:
一旦調用hashcode,偏向鎖將被撤銷,hashcode被保存占位mark word,對象被打回無鎖狀態
- 那偏偏這會就是有線程硬性使用對象的鎖呢?
對象再也回不到偏向鎖狀態而是升級為重量級鎖。hash code跟隨mark word被移動到c的object monitor,從那裡取
本文由傳智教育博學谷 - 狂野架構師教研團隊發佈
如果本文對您有幫助,歡迎關註和點贊;如果您有任何建議也可留言評論或私信,您的支持是我堅持創作的動力
轉載請註明出處!