System.identityHashCode(obj) 與 obj.hashcode()

簡介

最近在看dubbo源碼時(shí),經(jīng)巢娲瘢看到System.identityHashCode(obj) 的使用粘捎,想了解一下這個(gè)跟我們平常的hashcode方法又有啥異同薇缅,所以本篇簡單的探討一下攒磨。

概念

1、hashCode是 java.lang.Object.hashCode() 或者 java.lang.System.identityHashCode(obj) 會(huì)返回的值。他是一個(gè)對象的身份標(biāo)識(shí)泻骤。官方稱呼為:標(biāo)識(shí)哈希碼( identity hash code)。

2演痒、哪些特點(diǎn)?
(1)一個(gè)對象在其生命期中 identity hash code 必定保持不變趋惨;
(2)如果a == b器虾,那么他們的System.identityHashCode() 必須相等;
如果他們的System.identityHashCode() 不相等欧芽,那他們必定不是同一個(gè)對象(逆否命題與原命題真實(shí)性總是相同)葛圃;
(3)如果System.identityHashCode() 相等的話憎妙,并不能保證 a == b(畢竟這只是一個(gè)散列值厘唾,是允許沖突的)龙誊。
3、有什么作用载迄?
加速對象去重:由特征2可知护昧,只要判斷出兩個(gè)對象的hashCode不一致魂迄,就知道這兩個(gè)對象不是同一個(gè);又因?yàn)閔ashCode()的性能比 " == "性能高得多惋耙,所以多數(shù)時(shí)候捣炬,用它來判斷重復(fù)绽榛。

擴(kuò)展:為啥hashCode()性能高湿酸?
因?yàn)閔ashCode()的結(jié)果算出來后緩存起來灭美,下次調(diào)用直接用不需要重新計(jì)算推溃,提高性能

identityHashCode

看官方提供的API , 對System.identityHashCode()的解釋為 :
public static int identityHashCode([Object] x)

返回給定對象的哈希碼,該代碼與默認(rèn)的方法 hashCode() 返回的代碼一樣铁坎,無論給定對象的類是否重寫 hashCode()。null 引用的哈希碼為 0犁苏。

obj.hashcode()

hashCode()方法是頂級(jí)類Object類的提供的一個(gè)方法硬萍,所有的類都可以進(jìn)行對hashCode方法重寫。這時(shí)hash值計(jì)算根據(jù)重寫后的hashCode方法計(jì)算

異同

從上面的概念可以看出identityHashCode是根據(jù)Object類hashCode()方法來計(jì)算hash值围详,無論子類是否重寫了hashCode()方法朴乖。而obj.hashcode()是根據(jù)obj的hashcode()方法計(jì)算hash值

驗(yàn)證

    @Test
    public void testHashCode() {
        TestExample example = new TestExample();
        int exampleCode = System.identityHashCode(example);
        int exampleCode2 = System.identityHashCode(example);
        int exampleHashcode = example.hashCode();
        System.out.println("example identityHashCode:" + exampleCode);
        System.out.println("example2 identityHashCode:" + exampleCode2);
        System.out.println("example Hashcode:" + exampleHashcode);
        String str = "dd";
        String str2 = "dd";
        int strCode = System.identityHashCode(str);
        int strHashCode = str.hashCode();
        int str2HashCode = str.hashCode();
        System.out.println("str identityHashCode:" + strCode);
        System.out.println("str hashcode:" + strHashCode);
        System.out.println("str2 hashcode:" + str2HashCode);
    }
輸出:
example identityHashCode:1144748369
example2 identityHashCode:1144748369
example Hashcode:1144748369
str identityHashCode:340870931
str hashcode:3200
str2 hashcode:3200

結(jié)果分析:
(1)從上面樣例可以看出助赞,TestExample 對象沒重寫HashCode()方法,所以兩個(gè)都是調(diào)用Object的HashCode()方法哩都,自然結(jié)果一樣。
而String重寫了HashCode()方法咐汞,identityHashCode和HashCode結(jié)果自然不一樣化撕。
(2)str和str2的hashCode是相同的,是因?yàn)镾tring類重寫了hashCode方法约炎,它根據(jù)String的值來確定hashCode的值圾浅,所以只要值一樣,hashCode就會(huì)一樣狸捕。

hashCode如何計(jì)算的喷鸽?

JDK8 hashCode( )源碼:
進(jìn)入openjdk\jdk\src\share\classes\java\lang目錄下,可以看到 Object.java源碼

public native int hashCode();

即該方法是一個(gè)本地方法灸拍,Java將調(diào)用本地方法庫對此方法的實(shí)現(xiàn)做祝。由于Object類中有JNI方法調(diào)用,按照J(rèn)NI的規(guī)則鸡岗,應(yīng)當(dāng)生成JNI 的頭文件混槐,在此目錄下執(zhí)行javah -jni java.lang.Object 指令,將生成一個(gè)java_lang_Object.h頭文件轩性,

java_lang_Object.h頭文件關(guān)于hashcode方法的信息如下所示:

/*
 * Class:     java_lang_Object
 * Method:    hashCode
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_java_lang_Object_hashCode
  (JNIEnv *, jobject);
1. Object對象的hashCode()方法在C語言文件Object.c中實(shí)現(xiàn)

打開openjdk\jdk\src\share\native\java\lang目錄声登,查看Object.c文件,可以看到hashCode()的方法被注冊成有JVM_IHashCode方法指針來處理:

/*-
 *      Implementation of class Object
 *
 *      former threadruntime.c, Sun Sep 22 12:09:39 1991
 */

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

#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
//使用了上面生成的java_lang_Object.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},
};
2.JVM_IHashCode方法指針

在 openjdk\hotspot\src\share\vm\prims\jvm.cpp中定義揣苏,如下:

// java.lang.Object ///////////////////////////////////////////////


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

如上可以看出悯嗓,JVM_IHashCode方法中調(diào)用了ObjectSynchronizer::FastHashCode方法

3. ObjectSynchronizer::fashHashCode方法的實(shí)現(xiàn):

ObjectSynchronizer::fashHashCode()方法在hotspot\src\share\vm\runtime\synchronizer.cpp

// 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:
//
//最終生成hash的方法
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 ;            // for sensitivity testing
  } else
  if (hashCode == 3) {
     value = ++GVars.hcSequence ;
  } 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.
     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方法的實(shí)現(xiàn),該方法最終會(huì)返回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;
    }
  //調(diào)用get_next_hash生成hashcode
    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;
}

從上面代碼可以看出生成hash最終由get_next_hash函數(shù)生成舒岸,該函數(shù)提供了基于某個(gè)hashCode 變量值的六種方法。怎么生成最終值取決于hashCode這個(gè)變量值芦圾。

0 - 使用Park-Miller偽隨機(jī)數(shù)生成器(跟地址無關(guān))
1 - 使用地址與一個(gè)隨機(jī)數(shù)做異或(地址是輸入因素的一部分)
2 - 總是返回常量1作為所有對象的identity hash code(跟地址無關(guān))
3 - 使用全局的遞增數(shù)列(跟地址無關(guān))
4 - 使用對象地址的“當(dāng)前”地址來作為它的identity hash code(就是當(dāng)前地址)
5 - 使用線程局部狀態(tài)來實(shí)現(xiàn)Marsaglia's xor-shift隨機(jī)數(shù)生成(跟地址無關(guān))蛾派,從注釋中可以看到:這可能是最好的hashcode生成實(shí)現(xiàn)—在未來的版本中可能會(huì)將此設(shè)置為默認(rèn)值
擴(kuò)展補(bǔ)充:Xorshift 算法介紹

Xorshift 隨機(jī)數(shù)生成器是 George Marsaglia 發(fā)明的一類偽隨機(jī)數(shù)生成器。它們通過和自己邏輯移位后的數(shù)進(jìn)行異或操作來生成序列中的下一個(gè)數(shù)个少。這在現(xiàn)代計(jì)算機(jī)體系結(jié)構(gòu)非澈檎В快。它們是線性反饋移位寄存器的一個(gè)子類夜焦,其簡單的實(shí)現(xiàn)使它們速度更快且使用更少的空間壳澳。然而,必須仔細(xì)選擇合適參數(shù)以達(dá)到長周期茫经。
Xorshift生成器是非密碼安全的隨機(jī)數(shù)生成器中最快的一種巷波,只需要非常短的代碼和狀態(tài)萎津。雖然它們沒有進(jìn)一步改進(jìn)以通過統(tǒng)計(jì)檢驗(yàn),這個(gè)缺點(diǎn)非常著名且容易修改(Marsaglia 在原來的論文中指出)抹镊,用復(fù)合一個(gè)非線性函數(shù)的方式锉屈,可以得到比如像 xorshift+ 或 xorshift* 生成器。一個(gè)簡單的C語言實(shí)現(xiàn)的 xorshift+ 生成器通過了所有的 BigCrush 的測試(比 Mersenne Twister 算法和 WELL 算法的失敗次數(shù)減少了一個(gè)數(shù)量級(jí))垮耳,而且在 x86 上產(chǎn)生一個(gè)隨機(jī)數(shù)通常只需要不到十個(gè)時(shí)鐘周期颈渊,多虧了指令流水線。

VM到底用的是哪種方法终佛?
在openjdk\hotspot\src\share\vm\runtime\globals.hpp定義
JDK 8 和 JDK 9 默認(rèn)值:

product(intx, hashCode, 5,"(Unstable) select hashCode generation algorithm") ;

JDK 8 以前默認(rèn)值:

product(intx, hashCode, 0,"(Unstable) select hashCode generation algorithm") ;
不同的JDK俊嗽,生成方式不一樣。

注意:
雖然方式不一樣铃彰,但有個(gè)共同點(diǎn):java生成的hashCode和對象內(nèi)存地址沒什么關(guān)系绍豁。

修改生成方法

HotSpot提供了一個(gè)VM參數(shù)來讓用戶選擇identity hash code的生成方式:

-XX:hashCode

什么時(shí)候計(jì)算出來的

在VM里,Java對象會(huì)在首次真正使用到它的identity hash code(例如通過Object.hashCode() / System.identityHashCode())時(shí)調(diào)用VM里的函數(shù)來計(jì)算出值豌研,然后會(huì)保存在對象里妹田,后面對同一對象查詢其identity hash code時(shí)總是會(huì)返回最初記錄的值。
因此鹃共,不是對象創(chuàng)建時(shí)鬼佣。

參考

hashCode,一個(gè)實(shí)驗(yàn)引發(fā)的思考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末霜浴,一起剝皮案震驚了整個(gè)濱河市晶衷,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌阴孟,老刑警劉巖晌纫,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異永丝,居然都是意外死亡锹漱,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進(jìn)店門慕嚷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哥牍,“玉大人,你說我怎么就攤上這事喝检⌒崂保” “怎么了?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵挠说,是天一觀的道長澡谭。 經(jīng)常有香客問我,道長损俭,這世上最難降的妖魔是什么蛙奖? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任潘酗,我火速辦了婚禮,結(jié)果婚禮上外永,老公的妹妹穿的比我還像新娘崎脉。我一直安慰自己,他們只是感情好伯顶,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布囚灼。 她就那樣靜靜地躺著,像睡著了一般祭衩。 火紅的嫁衣襯著肌膚如雪灶体。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天掐暮,我揣著相機(jī)與錄音蝎抽,去河邊找鬼。 笑死路克,一個(gè)胖子當(dāng)著我的面吹牛樟结,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播精算,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼瓢宦,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了灰羽?” 一聲冷哼從身側(cè)響起驮履,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎廉嚼,沒想到半個(gè)月后玫镐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡怠噪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年恐似,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片傍念。...
    茶點(diǎn)故事閱讀 39,965評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡矫夷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出捂寿,到底是詐尸還是另有隱情口四,我是刑警寧澤孵运,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布秦陋,位于F島的核電站,受9級(jí)特大地震影響治笨,放射性物質(zhì)發(fā)生泄漏驳概。R本人自食惡果不足惜赤嚼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望顺又。 院中可真熱鬧更卒,春花似錦、人聲如沸稚照。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽果录。三九已至上枕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間弱恒,已是汗流浹背辨萍。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留返弹,地道東北人锈玉。 一個(gè)月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像义起,于是被迫代替她去往敵國和親拉背。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評論 2 355

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

  • java.lang.Object類中有兩個(gè)非常重要的方法: 1publicbooleanequals(Object...
    小陳阿飛閱讀 681評論 1 1
  • 集合框架: 1)特點(diǎn):存儲(chǔ)對象并扇;長度可變去团;存儲(chǔ)對象的類型可不同2)Collection(1)List:有序的;元素...
    Demo_Yang閱讀 1,260評論 0 4
  • 明弘治五年(1492年)戶部尚書葉淇在徽商的支持下推行折色制度穷蛹,規(guī)定鹽商可以納銀向相關(guān)機(jī)構(gòu)領(lǐng)取鹽引而不必在再...
    會(huì)飛的貓666閱讀 356評論 0 0
  • 因?yàn)閼型僚悖摌s,又打的肴熏,好貴啊鬼雀。。對不起爸爸媽媽蛙吏。對不起
    煙雨初婷閱讀 83評論 0 0
  • 昨天的目標(biāo)都沒完成源哩,真是計(jì)劃不如變化。唯有早起鸦做,7點(diǎn)之前的時(shí)間才是屬于我自己的励烦,計(jì)劃今晚10點(diǎn)半之前睡,明早4點(diǎn)半...
    章艷華閱讀 142評論 0 0