面試必問的HashCode技術內幕

来源:https://www.cnblogs.com/jiagooushi/archive/2022/08/01/16540424.html
-Advertisement-
Play Games

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不是記憶體地址(嚴格的說,肯定不是直接取的記憶體地址)

file

思考一下,為什麼不能直接用記憶體地址呢?

  • 提示:jvm垃圾收集演算法,對象遷移……

那麼它到底是什麼?如何生成的呢

2) 不是地址那在哪裡?

既然不是記憶體地址,那一定在某個地方存著,那在哪裡存著呢?

答案:在對象頭裡!(畫圖。類在jvm記憶體中的佈局)

file

對象頭分為兩部分,一部分是上面指向class描述的地址Klass,另一部分就是Markword

而我們這裡要找的hashcode在Markword里!(標記位意義,不用記!)

32位:

file

64位:
file

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());
        }

}

結果分析

file

file

結論:在你沒有調用的時候,這個值是空的,當第一次調用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

完全搜不到這個方法名,只有這個還湊合有點像,那這是個啥呢?
file

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
file

file

先說生成流程,留個印象:
file

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,從那裡取

本文由傳智教育博學谷 - 狂野架構師教研團隊發佈
如果本文對您有幫助,歡迎關註和點贊;如果您有任何建議也可留言評論或私信,您的支持是我堅持創作的動力
轉載請註明出處!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前言: 今天用for range寫了個demo,發現無論怎麼運行,最後的結果是一直是最後一個。自己思考過後,又和其他伙伴商量了下,最終算是解決了自己的疑惑。 正文: 下麵我們來看個例子: m := make(map[int]*int) arr := []int{1, 2, 3, 4, 5} for ...
  • 簡單記錄,分享下這段時間學習Flask所用過的資料 學習Flask的這段時間,我在網上找了挺多,也看了挺多的資料,有視頻,也有文檔教程。 然後我發現,這方面資料有點雜而不全,就沒有特別好的的教程可看,而且對於咱這樣的新手如果一開始就去看官方的文檔,也看的迷迷糊糊,最後發現還是什麼都不會。 經過我這段 ...
  • 兄弟們,今天來實現一下用Python編寫密碼檢測器,並輸出詳細信息! 本次涉及知識點 文件讀寫 基礎語法 字元串處理 迴圈遍歷 代碼展示 # 導入系統包 import platform # 我給大家準備了一些資料,包括2022最新Python視頻教程、Python電子書10個G (涵蓋基礎、爬蟲、數 ...
  • 面向對象03 10.抽象類 abstract修飾符可以用來修飾方法也可以修飾類,如果修飾方法,那麼該方法就是抽象方法;如果修飾類,那麼該類就是抽象類 抽象類中可以沒有抽象方法,但是有抽象方法的類一定要聲明為抽象類 抽象類,不能使用new關鍵字來創建對象,它是用來讓子類繼承的 抽象方法,只有方法的聲明 ...
  • indexOf和subString取值走向圖;首先簡單介紹這者的作用,具體可以看官方API 1.indexOf的作用: 就是獲取某個字元串的其中具體一個字元的位置 2.subString的作用: 就是大家熟悉的切割,從那裡到那裡比如,從第一個到第五個等;當這個方法是重載的,不只有我說的這個方法;具體 ...
  • 明敏 曉查 發自 凹非寺 量子位 報道 | 公眾號 QbitAI 程式 bug 也能負負得正嗎? 還真可以。 比如程式員們再熟悉不過的排序演算法,通過兩個“bug”居然能歪打正著,實在令人匪夷所思。 請看這位程式員寫的數組升序排序代碼: for i = 1 to n do for j = 1 to n ...
  • 基礎確認:HTML、CSS、JavaScript AJAX可以: 不刷新頁面更新網頁 在頁面載入後從伺服器請求數據 在頁面載入後從伺服器接收數據 在後臺向伺服器發送數據 Ajax 的核心是 XMLHttpRequest 對象,用於和伺服器交換數據。 xmlhttp.open("GET","ajax_ ...
  • 多商戶商城系統,也稱為B2B2C(BBC)平臺電商模式多商家商城系統。可以快速幫助企業搭建類似拼多多/京東/天貓/淘寶的綜合商城。 多商戶商城系統支持商家入駐加盟,同時滿足平臺自營、旗艦店等多種經營方式。平臺可以通過收取商家入駐費,訂單交易服務費,提現手續費,簡訊通道費等多手段方式,實現整體盈利。 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...