System.identityHashCode和hashCode的区别及说明

 更新时间:2024年11月13日 08:49:14   作者:青一叶舟  
String调用hashCode()和System.identityHashCode()返回值不同是因为String重写了hashCode()方法,而System.identityHashCode()返回对象的内存地址哈希值;Test调用两个方法返回值相同是因为Test没有重写hashCode()方法,因此两者调用底层的JVM_IHashCode方法返回相同值

System.identityHashCode和hashCode的区别

测试:

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

运行结果:

为什么String调用hashCode()和System.identityHashCode()返回值不同呢?为什么Test调用hashCode()和System.identityHashCode()返回值又相同呢?

System.identityHashCode()和hashCode()到底有什么不同呢?这里个人简单分析一下,有不足之处劳烦指出。

System.identityHashCode底层实现

System.identityHashCode底层调用C语言System.c来实现

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

其中调用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;
}

其中,调用的核心方法是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;
}

根据hashcode值,可以分为以下方法:

0- 随机生成值

1- 获取对象的实际内存地址

2- 返回1,用于灵敏度测试

3- 自增 4- 第二种的变种

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

jdk1.8前,默认hashcode为0,可通过globals.hpp文件查看,调用第一个方法,随机生成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默认值来修改调用方法

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

Object.hashCode底层实现

通过查看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},
};

发现还是和System.identityHashCode一样都是调用JVM_IHashCode方法。

总结

  • 当hashCode()未被重写时,System.identityHashCode()和hashCode()返回值相同,都是调用底层JVM_IHashCode方法
  • 当hashCode()被重写,则System.identityHashCode()和hashCode()返回值不同。hashCode()返回重写结果,System.identityHashCode()返回底层生成hashcode

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java爬虫Gecco工具抓取新闻实例

    java爬虫Gecco工具抓取新闻实例

    本篇文章主要介绍了JAVA 爬虫Gecco工具抓取新闻实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2016-10-10
  • Java的后台文件夹下文件的遍历完整代码

    Java的后台文件夹下文件的遍历完整代码

    这篇文章主要介绍了Java的后台文件夹下文件的遍历完整代码,首先分享了java中遍历一个文件夹里边的所有文件,然后介绍了用Java遍历一个文件夹并获取它里面的所有内容详细代码,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Java设计模式开发中使用观察者模式的实例教程

    Java设计模式开发中使用观察者模式的实例教程

    这篇文章主要介绍了Java设计模式开发中使用观察者模式的实例教程,松耦合和逻辑清晰的消息监听是观察者模式的大特色,需要的朋友可以参考下
    2016-04-04
  • BeanUtils.copyProperties使用总结以及注意事项说明

    BeanUtils.copyProperties使用总结以及注意事项说明

    这篇文章主要介绍了BeanUtils.copyProperties使用总结以及注意事项说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • Java并发编程之synchronized底层实现原理分析

    Java并发编程之synchronized底层实现原理分析

    这篇文章主要介绍了Java并发编程之synchronized底层实现原理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • SpringBoot整合EasyExcel实现大规模数据的并行导出与压缩下载

    SpringBoot整合EasyExcel实现大规模数据的并行导出与压缩下载

    在 Spring Boot 应用中,整合 EasyExcel 实现并行导出数据并进行 Zip 压缩下载可以极大地提高数据处理效率和用户体验,文中通过代码示例介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2024-10-10
  • 手写java性能测试框架的实现示例

    手写java性能测试框架的实现示例

    这篇文章主要为大家介绍了java实现性能测试框架示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • Spring如何集成ibatis项目并实现dao层基类封装

    Spring如何集成ibatis项目并实现dao层基类封装

    这篇文章主要介绍了Spring如何集成ibatis项目并实现dao层基类封装,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • java 音频转换wav格式标准音频的操作

    java 音频转换wav格式标准音频的操作

    这篇文章主要介绍了java 音频转换wav格式标准音频的操作,主要是使用ffmpeg命令进行转换,该工具类主要是为了将各类音频转为wav标准格式,其中可以调节采样率、声道数等指标,依赖maven环境,需要的朋友可以参考下
    2021-10-10
  • 详解spring boot引入外部jar包的坑

    详解spring boot引入外部jar包的坑

    本篇文章主要介绍了spring boot引入外部jar的坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12

最新评论