最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

System.identityHashCode和hashCode的區(qū)別及說明

 更新時間:2024年11月13日 08:49:14   作者:青一葉舟  
String調(diào)用hashCode()和System.identityHashCode()返回值不同是因為String重寫了hashCode()方法,而System.identityHashCode()返回對象的內(nèi)存地址哈希值;Test調(diào)用兩個方法返回值相同是因為Test沒有重寫hashCode()方法,因此兩者調(diào)用底層的JVM_IHashCode方法返回相同值

System.identityHashCode和hashCode的區(qū)別

測試:

public class HashCodeDemo {

    public static void main(String[] args) {
        String str = new String("test");
        String str2= new String("test");

        System.out.println(str.hashCode());
        System.out.println(str2.hashCode());

        System.out.println(System.identityHashCode(str));
        System.out.println(System.identityHashCode(str2));

        System.out.println("----------------test------------");

        Test test = new Test();
        Test test2 = new Test();

        System.out.println(test.hashCode());
        System.out.println(test2.hashCode());

        System.out.println(System.identityHashCode(test));
        System.out.println(System.identityHashCode(test2));
    }
}

運行結(jié)果:

為什么String調(diào)用hashCode()和System.identityHashCode()返回值不同呢?為什么Test調(diào)用hashCode()和System.identityHashCode()返回值又相同呢?

System.identityHashCode()和hashCode()到底有什么不同呢?這里個人簡單分析一下,有不足之處勞煩指出。

System.identityHashCode底層實現(xiàn)

System.identityHashCode底層調(diào)用C語言System.c來實現(xiàn)

openjdk源碼路徑:jdk-935758609767\src\share\native\java\lang\System.c

// 核心代碼:
Java_java_lang_System_identityHashCode(JNIEnv *env, jobject this, jobject x)
{
    return JVM_IHashCode(env, x);
}

其中調(diào)用jvm.cpp的JVM_IHashCode()方法

hotspot源碼路徑:hotspot-37240c1019fd\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

再來看一下synchronizer.cpp的ObjectSynchronizer::FastHashCode()方法

hotspot源碼路徑:hotspot-37240c1019fd\src\share\vm\runtime\synchronizer.cpp

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

其中,調(diào)用的核心方法是get_next_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;
}

根據(jù)hashcode值,可以分為以下方法:

0- 隨機生成值

1- 獲取對象的實際內(nèi)存地址

2- 返回1,用于靈敏度測試

3- 自增 4- 第二種的變種

5- xorshift算法,有興趣可以看一下https://en.wikipedia.org/wiki/Xorshift

jdk1.8前,默認hashcode為0,可通過globals.hpp文件查看,調(diào)用第一個方法,隨機生成hashcode

globals.hpp源碼路徑:hotspot\src\share\vm\runtime\globals.hpp

product(intx, hashCode, 0,“(Unstable) select hashCode generation algorithm”)

jdk1.8后,默認為5,使用xorshift 算法生成hashcode

product(intx, hashCode, 5,“(Unstable) select hashCode generation algorithm”)

同時可以通過-XX:hashCode=N來修改jvm默認值來修改調(diào)用方法

查看jvm默認值java -XX:+PrintFlagsFinal -version

Object.hashCode底層實現(xiàn)

通過查看openjdk源碼Object.c

Object.c源碼路徑:jdk-935758609767\src\share\native\java\lang\Object.c

static JNINativeMethod methods[] = {
    {"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},
};

發(fā)現(xiàn)還是和System.identityHashCode一樣都是調(diào)用JVM_IHashCode方法。

總結(jié)

  • 當hashCode()未被重寫時,System.identityHashCode()和hashCode()返回值相同,都是調(diào)用底層JVM_IHashCode方法
  • 當hashCode()被重寫,則System.identityHashCode()和hashCode()返回值不同。hashCode()返回重寫結(jié)果,System.identityHashCode()返回底層生成hashcode

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Springboot整合hutool驗證碼的實例代碼

    Springboot整合hutool驗證碼的實例代碼

    在 Spring Boot 中,你可以將 Hutool 生成驗證碼的功能集成到 RESTful API 接口中,這篇文章主要介紹了Springboot整合hutool驗證碼,需要的朋友可以參考下
    2024-08-08
  • java7 簡化變參方法調(diào)用實例方法

    java7 簡化變參方法調(diào)用實例方法

    在本篇文章里我們給大家整理的是關(guān)于java7 簡化變參方法調(diào)用實例方法以及實例代碼,需要的朋友們學習下。
    2019-11-11
  • 詳解Spring Aop實例之AspectJ注解配置

    詳解Spring Aop實例之AspectJ注解配置

    本篇文章主要介紹了詳解Spring Aop實例之AspectJ注解配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • 基于java構(gòu)造方法Vector遍歷元素源碼分析

    基于java構(gòu)造方法Vector遍歷元素源碼分析

    本篇文章是關(guān)于ava構(gòu)造方法Vector源碼分析系列文章,本文主要介紹了Vector遍歷元素的源碼分析,有需要的朋友可以借鑒參考下,希望可以有所幫助
    2021-09-09
  • 基于SpringCloud手寫一個簡易版Sentinel

    基于SpringCloud手寫一個簡易版Sentinel

    SpringCloud Alibaba Sentinel是當前最為流行一種熔斷降級框架,簡單易用的方式可以快速幫助我們實現(xiàn)服務(wù)的限流和降級,保證服務(wù)的穩(wěn)定性。
    2021-05-05
  • Java代碼實現(xiàn)對properties文件有序的讀寫的示例

    Java代碼實現(xiàn)對properties文件有序的讀寫的示例

    本篇文章主要介紹了Java代碼實現(xiàn)對properties文件有序的讀寫的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • 求1000階乘的結(jié)果末尾有多少個0

    求1000階乘的結(jié)果末尾有多少個0

    題目是:求1000!的結(jié)果末尾有多少個0,解題思路:兩個素數(shù)2、5,相乘即可得到10,我們可以認為,有多少組2、5,結(jié)尾就有多少個0,下面是代碼,需要的朋友可以參考下
    2014-02-02
  • 利用JDBC的PrepareStatement打印真實SQL的方法詳解

    利用JDBC的PrepareStatement打印真實SQL的方法詳解

    PreparedStatement是預(yù)編譯的,對于批量處理可以大大提高效率. 也叫JDBC存儲過程,下面這篇文章主要給大家介紹了關(guān)于利用JDBC的PrepareStatement打印真實SQL的方法,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-07-07
  • Kotlin 單例實例詳解

    Kotlin 單例實例詳解

    這篇文章主要介紹了Kotlin 單例實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • java項目構(gòu)建Gradle的使用教程

    java項目構(gòu)建Gradle的使用教程

    這篇文章主要為大家介紹了java項目構(gòu)建Gradle的使用教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-03-03

最新評論

铁岭县| 天水市| 田东县| 清流县| 井研县| 含山县| 龙山县| 汉源县| 曲沃县| 将乐县| 瓦房店市| 江永县| 鲁山县| 师宗县| 宣武区| 娱乐| 那曲县| 澄江县| 京山县| 福鼎市| 稷山县| 礼泉县| 武汉市| 兴隆县| 清涧县| 邵阳县| 武清区| 富源县| 二连浩特市| 万宁市| 樟树市| 稻城县| 盖州市| 靖西县| 河北区| 上饶市| 巴楚县| 永定县| 岑溪市| 娱乐| 阳信县|