HashCode解析

眾所周知杨何,Java語言中占遥,Object對象有個特殊的方法:hashcode(), hashcode()表示的是JVM虛擬機為這個Object對象分配的一個int類型的數(shù)值堕伪,JVM會使用對象的hashcode值來提高對HashMap纺弊、Hashtable哈希表存取對象的使用效率阿逃。而在很多網(wǎng)上的教程中告訴我們的是hashcode返回的是對象的內(nèi)存地址。然而實際使用中會發(fā)現(xiàn)哈希值存在負(fù)數(shù)的情況时肿,而內(nèi)存地址肯定不會用負(fù)數(shù)表示庇茫,因此有了本文對其底層實現(xiàn)進一步進行探索。須知的是螃成,不同的JRE對這些方法的實現(xiàn)各有不同旦签,只是遵循著Java對這些方法所訂立的規(guī)范進行設(shè)計的,本文基于的是openJDK的源碼寸宏。
首先我們確認(rèn)一下hashcode()方法返回值到底是不是內(nèi)存地址:

import java.lang.reflect.Field;  
import sun.misc.Unsafe;  
  
public class HashcodeTest {  
      
    private static Unsafe unsafe;  
  
    static {  
        try {  
            Field field = Unsafe.class.getDeclaredField("theUnsafe");  
            field.setAccessible(true);  
            unsafe = (Unsafe) field.get(null);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    public static long addressOf(Object o) throws Exception {  
          
        Object[] array = new Object[] { o };  
  
        long baseOffset = unsafe.arrayBaseOffset(Object[].class);  
        int addressSize = unsafe.addressSize();  
        long objectAddress;  
        switch (addressSize) {  
        case 4:  
            objectAddress = unsafe.getInt(array, baseOffset);  
            break;  
        case 8:  
            objectAddress = unsafe.getLong(array, baseOffset);  
            break;  
        default:  
            throw new Error("unsupported address size: " + addressSize);  
        }  
        return (objectAddress);  
    }  
  
    public static void main(String... args) throws Exception {  
        Object object = "object"; 
        long address_1 = addressOf(object);  
        int address_2 = object.hashCode();
        System.out.println("Addess: " + address_1+" "+address_2);  
  
    }  
}  

代碼中用到了大名鼎鼎的Unsafe類宁炫,它提供了繞開"安全"的JVM機制直接調(diào)用"native"的底層方法的功能,在java.concurrent包中大量使用了其提供的CAS功能氮凝。

Screen Shot 2019-02-17 at 10.14.18 PM.png

由結(jié)果中可以看出兩者是截然不同的兩個整型數(shù)羔巢。
那JDK到底是通過什么策略來生成哈希值的呢?
查看openJDK 關(guān)于 java.lang.Object類及其hashcode()方法的定義

public native int hashCode();

即該方法是一個本地方法罩阵,Java將調(diào)用本地方法庫對此方法的實現(xiàn)竿秆。由于Object類中有JNI方法調(diào)用,按照J(rèn)NI的規(guī)則稿壁,應(yīng)當(dāng)生成JNI 的頭文件袍辞,在此目錄下執(zhí)行javah -jni java.lang.Object 指令,將生成一個java_lang_Object.h頭文件常摧,該頭文件將在后面用到它:

/*
 * Class:     java_lang_Object
 * Method:    hashCode
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_java_lang_Object_hashCode
  (JNIEnv *, jobject);

Object對象的hashCode()方法在C語言文件Object.c中實現(xiàn)

#include <stdio.h>
#include <signal.h>
#include <limits.h>

#include "jni.h"
#include "jni_util.h"
#include "jvm.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},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
    (*env)->RegisterNatives(env, cls,
                            methods, sizeof(methods)/sizeof(methods[0]));
}

JNIEXPORT jclass JNICALL
Java_java_lang_Object_getClass(JNIEnv *env, jobject this)
{
    if (this == NULL) {
        JNU_ThrowNullPointerException(env, NULL);
        return 0;
    } else {
        return (*env)->GetObjectClass(env, this);
    }
}

JVM_IHashCode方法指針在 openjdk\hotspot\src\share\vm\prims\jvm.cpp中定義

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

ObjectSynchronizer::fashHashCode方法的實現(xiàn)

// 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:
//

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 = 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 = 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方法的實現(xiàn),該方法最終會返回我們期望已久的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;
    }
    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;
}

從上面的追根溯源可以發(fā)現(xiàn)威创,在openJDK中實現(xiàn)了多種不同的hash值計算策略落午,只有一種是直接返回對象的內(nèi)存地址。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末肚豺,一起剝皮案震驚了整個濱河市溃斋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吸申,老刑警劉巖梗劫,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件享甸,死亡現(xiàn)場離奇詭異,居然都是意外死亡梳侨,警方通過查閱死者的電腦和手機蛉威,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來走哺,“玉大人蚯嫌,你說我怎么就攤上這事”铮” “怎么了择示?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長晒旅。 經(jīng)常有香客問我栅盲,道長,這世上最難降的妖魔是什么废恋? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任谈秫,我火速辦了婚禮,結(jié)果婚禮上拴签,老公的妹妹穿的比我還像新娘孝常。我一直安慰自己,他們只是感情好蚓哩,可當(dāng)我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布构灸。 她就那樣靜靜地躺著,像睡著了一般岸梨。 火紅的嫁衣襯著肌膚如雪喜颁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天曹阔,我揣著相機與錄音半开,去河邊找鬼。 笑死赃份,一個胖子當(dāng)著我的面吹牛寂拆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播抓韩,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼纠永,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了谒拴?” 一聲冷哼從身側(cè)響起尝江,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎英上,沒想到半個月后炭序,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體啤覆,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年惭聂,在試婚紗的時候發(fā)現(xiàn)自己被綠了窗声。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡彼妻,死狀恐怖嫌佑,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情侨歉,我是刑警寧澤屋摇,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站幽邓,受9級特大地震影響炮温,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜牵舵,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一柒啤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧畸颅,春花似錦担巩、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至送火,卻和暖如春拳话,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背种吸。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工弃衍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人坚俗。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓镜盯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親猖败。 傳聞我的和親對象是個殘疾皇子形耗,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Java8張圖 11、字符串不變性 12辙浑、equals()方法、hashCode()方法的區(qū)別 13拟糕、...
    Miley_MOJIE閱讀 3,707評論 0 11
  • 所有知識點已整理成app app下載地址 J2EE 部分: 1.Switch能否用string做參數(shù)判呕? 在 Jav...
    侯蛋蛋_閱讀 2,440評論 1 4
  • 簡介 最近在看dubbo源碼時倦踢,經(jīng)常看到System.identityHashCode(obj) 的使用侠草,想了解一...
    多喝水JS閱讀 9,299評論 4 5
  • 事件:今天孩子洗完腳辱挥,要洗自己的襪子,可是襪子被他爸爸已經(jīng)洗好了边涕,兒子就各種不開心晤碘,踢水、大聲喘氣功蜓、哭泣……思維筆...
    晶晶_37cd閱讀 238評論 0 0
  • 外婆(一) 在記憶中园爷,小時候除了父母之外,外婆就是那個能為我們姐弟幾個遮風(fēng)擋雨的人式撼。 ...
    蕭肖的一棵樹閱讀 719評論 4 14