hashCode的內(nèi)幕
tips:面試常問/常用/常出錯
hashCode到底是什么?是不是對象的內(nèi)存地址?
1) 直接用內(nèi)存地址?
目標:通過一個Demo驗證這個hasCode到底是不是內(nèi)存地址
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 {
//目標:只要發(fā)生重復(fù),說明hashcode不是內(nèi)存地址,但還需要證明(JVM代碼證明)
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
int num = 0;
for (int i = 0; i < 150000; i++) {
//創(chuàng)建新的對象
Object object = new Object();
if (integerList.contains(object.hashCode())) {
num++;//發(fā)生重復(fù)(內(nèi)存地址肯定不會重復(fù))
} else {
integerList.add(object.hashCode());//沒有重復(fù)
}
}
System.out.println(num + "個hashcode發(fā)生重復(fù)");
System.out.println("List合計大小" + integerList.size() + "個");
}
}
15萬個循環(huán),發(fā)生了重復(fù),說明hashCode不是內(nèi)存地址(嚴格的說,肯定不是直接取的內(nèi)存地址)
思考一下,為什么不能直接用內(nèi)存地址呢?
- 提示:jvm垃圾收集算法,對象遷移……
那么它到底是什么?如何生成的呢
2) 不是地址那在哪里?
既然不是內(nèi)存地址,那一定在某個地方存著,那在哪里存著呢?
答案:在對象頭里!(畫圖。類在jvm內(nèi)存中的布局)
對象頭分為兩部分,一部分是上面指向class描述的地址Klass,另一部分就是Markword
而我們這里要找的hashcode在Markword里!(標記位意義,不用記!)
32位:
64位:
image.png
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("-------------------------");
//調(diào)用之前打印a對象的頭信息
//以表格的形式打印對象布局
System.out.println(ClassLayout.parseInstance(a).toPrintable());
System.out.println("-------------------------");
//調(diào)用后再打印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());
}
}
結(jié)果分析
結(jié)論:在你沒有調(diào)用的時候,這個值是空的,當?shù)谝淮握{(diào)用hashCode方法時,會生成,加鎖以后,不知道去哪里了……
4) 怎么生成的?
接上文 , 我們追究一下,它詳細的生成及移動過程。
我們都知道,這貨是個本地方法
public native int hashCode();
那就需要借助上面提到的辦法,通過JVM虛擬機源碼,查看hashcode的生成
1)先從Object.c開始找hashCode映射
srcsharenativejavalangObject.c
JNIEXPORT void JNICALL//jni調(diào)用
//全路徑:java_lang_Object_registerNatives是java對應(yīng)的包下方法
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
//jni環(huán)境調(diào)用;下面的參數(shù)methods對應(yīng)的java方法
(*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0]));
}
JAVA--------------------->C++函數(shù)對應(yīng)
//JAVA方法(返回值)----->C++函數(shù)對象
static JNINativeMethod methods[] = {
//JAVA方法 返回值 (參數(shù)) c++函數(shù)
{"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
完全搜不到這個方法名,只有這個還湊合有點像,那這是個啥呢?
srcsharevmprimsjvm.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是一個預(yù)加載宏,增加一些樣板代碼到j(luò)vm的所有function中
這個api是位于本地方法與jdk之間的一個連接層。
所以,此處才是生成hashCode的邏輯!
*/
JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
JVMWrApper("JVM_IHashCode");
//調(diào)用了ObjectSynchronizer對象的FastHashCode
return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
JVM_END
3)繼續(xù),
ObjectSynchronizer::FastHashCode
先說生成流程,留個印象:
intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
//是否開啟了偏向鎖(Biased:偏向,傾向)
if (UseBiasedLocking) {
//如果當前對象處于偏向鎖狀態(tài)
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");
//那么就撤銷偏向鎖(達到無鎖狀態(tài),revoke:廢除)
BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
obj = hobj() ;
//斷言下,看看是否撤銷成功(撤銷后為無鎖狀態(tài))
assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
}
}
// ……
ObjectMonitor* monitor = NULL;
markOop temp, test;
intptr_t hash;
//讀出一個穩(wěn)定的mark;防止對象obj處于膨脹狀態(tài);
//如果正在膨脹,就等他膨脹完畢再讀出來
markOop mark = ReadStableMark (obj);
//是否撤銷了偏向鎖(也就是無鎖狀態(tài))(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
//生成后,原子性設(shè)置,將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.
//如果已經(jīng)升級成了重量級鎖,那么找到它的monitor
//也就是我們所說的內(nèi)置鎖(objectMonitor),這是c里的數(shù)據(jù)類型
//因為鎖升級后,mark里的bit位已經(jīng)不再存儲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;
}
}
......略
問:
為什么要先撤銷偏向鎖到無鎖狀態(tài),再來生成hashcode呢?這跟鎖有什么關(guān)系?
答:
mark word里,hashcode存儲的字節(jié)位置被偏向鎖給占了!偏向鎖存儲了鎖持有者的線程id
(參考上面的markword圖)
擴展:關(guān)于hashCode的生成算法(了解)
// hashCode() generation :
// 涉及到c++算法領(lǐng)域,感興趣的同學自行研究
// 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() ;//返回隨機數(shù)
} 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.
//和地址相關(guān),但不是地址;右移+異或算法
intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3 ;
value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;//隨機數(shù)位移異或計算
} 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 隨機數(shù)算法(異或隨機算法)
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)總結(jié)
通過分析虛擬機源碼我們證明了hashCode不是直接用的內(nèi)存地址,而是采取一定的算法來生成
hashcode值的存儲在mark word里,與鎖共用一段bit位,這就造成了跟鎖狀態(tài)相關(guān)性
- 如果是偏向鎖:
一旦調(diào)用hashcode,偏向鎖將被撤銷,hashcode被保存占位mark word,對象被打回無鎖狀態(tài)
- 那偏偏這會就是有線程硬性使用對象的鎖呢?
對象再也回不到偏向鎖狀態(tài)而是升級為重量級鎖。hash code跟隨mark word被移動到c的object monitor,從那里取