1. hashcode

1.Object的hashcode

  1. 默认调用objecthashcode的话,会调用native方法,与本地相关。
  1. public native int hashCode();
  1. <br /> 来自 : [https://zhuanlan.zhihu.com/p/33915892](https://zhuanlan.zhihu.com/p/33915892)<br /> 下载完整的jdk呗[(](https://github.com/dmlloyd/openjdk/tree/jdk8u/jdk8u)[openJDK1.8](https://github.com/dmlloyd/openjdk/tree/jdk8u/jdk8u)[)](https://github.com/dmlloyd/openjdk/tree/jdk8u/jdk8u)。找到[Object.c](https://github.com/dmlloyd/openjdk/blob/jdk8u/jdk8u/jdk/src/share/native/java/lang/Object.c)文件,查看上面的方法映射表发现,hashCode被映射到了一个叫JVM_IHashCode上去了。
  1. static JNINativeMethod methods[] = {
  2. {"hashCode", "()I", (void *)&JVM_IHashCode},
  3. {"wait", "(J)V", (void *)&JVM_MonitorWait},
  4. {"notify", "()V", (void *)&JVM_MonitorNotify},
  5. {"notifyAll", "()V", (void *)&JVM_MonitorNotifyAll},
  6. {"clone", "()Ljava/lang/Object;", (void *)&JVM_Clone},
  7. };
  1. 顺藤摸瓜去看看JVM_IHashCode到底干了什么?熟悉的味道,在jvm.h里面有方法声明,那实现一定在jvm.cpp里面。不过[jvm.cpp](https://link.zhihu.com/?target=https%3A//github.com/dmlloyd/openjdk/blob/jdk8u/jdk8u/hotspot/src/share/vm/prims/jvm.cpp)对于JVM_IHashCode的实现调用的是ObjectSynchronizer::**FastHashCode**的方法。
  1. JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
  2. JVMWrapper("JVM_IHashCode");
  3. // as implemented in the classic virtual machine; return 0 if object is NULL
  4. return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
  5. JVM_END
  1. 发现声明在[synchronizer.hpp](https://link.zhihu.com/?target=https%3A//github.com/dmlloyd/openjdk/blob/jdk/jdk/src/hotspot/share/runtime/synchronizer.hpp) 实现在这里[synchronizer.cpp](https://link.zhihu.com/?target=https%3A//github.com/dmlloyd/openjdk/blob/jdk/jdk/src/hotspot/share/runtime/synchronizer.cpp)<br />
  1. // hashCode() generation :
  2. //
  3. // Possibilities:
  4. // * MD5Digest of {obj,stwRandom}
  5. // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
  6. // * A DES- or AES-style SBox[] mechanism
  7. // * One of the Phi-based schemes, such as:
  8. // 2654435761 = 2^32 * Phi (golden ratio)
  9. // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
  10. // * A variation of Marsaglia's shift-xor RNG scheme.
  11. // * (obj ^ stwRandom) is appealing, but can result
  12. // in undesirable regularity in the hashCode values of adjacent objects
  13. // (objects allocated back-to-back, in particular). This could potentially
  14. // result in hashtable collisions and reduced hashtable efficiency.
  15. // There are simple ways to "diffuse" the middle address bits over the
  16. // generated hashCode values:
  17. static inline intptr_t get_next_hash(Thread * Self, oop obj) {
  18. intptr_t value = 0;
  19. if (hashCode == 0) {
  20. // This form uses global Park-Miller RNG.
  21. // On MP system we'll have lots of RW access to a global, so the
  22. // mechanism induces lots of coherency traffic.
  23. value = os::random();
  24. } else if (hashCode == 1) {
  25. // This variation has the property of being stable (idempotent)
  26. // between STW operations. This can be useful in some of the 1-0
  27. // synchronization schemes.
  28. intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3;
  29. value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom;
  30. } else if (hashCode == 2) {
  31. value = 1; // for sensitivity testing
  32. } else if (hashCode == 3) {
  33. value = ++GVars.hcSequence;
  34. } else if (hashCode == 4) {
  35. value = cast_from_oop<intptr_t>(obj);
  36. } else {
  37. // Marsaglia's xor-shift scheme with thread-specific state
  38. // This is probably the best overall implementation -- we'll
  39. // likely make this the default in future releases.
  40. unsigned t = Self->_hashStateX;
  41. t ^= (t << 11);
  42. Self->_hashStateX = Self->_hashStateY;
  43. Self->_hashStateY = Self->_hashStateZ;
  44. Self->_hashStateZ = Self->_hashStateW;
  45. unsigned v = Self->_hashStateW;
  46. v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
  47. Self->_hashStateW = v;
  48. value = v;
  49. }
  50. value &= markOopDesc::hash_mask;
  51. if (value == 0) value = 0xBAD;
  52. assert(value != markOopDesc::no_hash, "invariant");
  53. TEVENT(hashCode: GENERATE);
  54. return value;
  55. }
  56. intptr_t ObjectSynchronizer::FastHashCode(Thread * Self, oop obj) {
  57. if (UseBiasedLocking) {
  58. // NOTE: many places throughout the JVM do not expect a safepoint
  59. // to be taken here, in particular most operations on perm gen
  60. // objects. However, we only ever bias Java instances and all of
  61. // the call sites of identity_hash that might revoke biases have
  62. // been checked to make sure they can handle a safepoint. The
  63. // added check of the bias pattern is to avoid useless calls to
  64. // thread-local storage.
  65. if (obj->mark()->has_bias_pattern()) {
  66. // Handle for oop obj in case of STW safepoint
  67. Handle hobj(Self, obj);
  68. // Relaxing assertion for bug 6320749.
  69. assert(Universe::verify_in_progress() ||
  70. !SafepointSynchronize::is_at_safepoint(),
  71. "biases should not be seen by VM thread here");
  72. BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
  73. obj = hobj();
  74. assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
  75. }
  76. }
  77. // hashCode() is a heap mutator ...
  78. // Relaxing assertion for bug 6320749.
  79. assert(Universe::verify_in_progress() || DumpSharedSpaces ||
  80. !SafepointSynchronize::is_at_safepoint(), "invariant");
  81. assert(Universe::verify_in_progress() || DumpSharedSpaces ||
  82. Self->is_Java_thread() , "invariant");
  83. assert(Universe::verify_in_progress() || DumpSharedSpaces ||
  84. ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
  85. ObjectMonitor* monitor = NULL;
  86. markOop temp, test;
  87. intptr_t hash;
  88. markOop mark = ReadStableMark(obj);
  89. // object should remain ineligible for biased locking
  90. assert(!mark->has_bias_pattern(), "invariant");
  91. if (mark->is_neutral()) {
  92. hash = mark->hash(); // this is a normal header
  93. if (hash) { // if it has hash, just return it
  94. return hash;
  95. }
  96. hash = get_next_hash(Self, obj); // allocate a new hash code
  97. temp = mark->copy_set_hash(hash); // merge the hash code into header
  98. // use (machine word version) atomic operation to install the hash
  99. test = obj->cas_set_mark(temp, mark);
  100. if (test == mark) {
  101. return hash;
  102. }
  103. // If atomic operation failed, we must inflate the header
  104. // into heavy weight monitor. We could add more code here
  105. // for fast path, but it does not worth the complexity.
  106. } else if (mark->has_monitor()) {
  107. monitor = mark->monitor();
  108. temp = monitor->header();
  109. assert(temp->is_neutral(), "invariant");
  110. hash = temp->hash();
  111. if (hash) {
  112. return hash;
  113. }
  114. // Skip to the following code to reduce code size
  115. } else if (Self->is_lock_owned((address)mark->locker())) {
  116. temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
  117. assert(temp->is_neutral(), "invariant");
  118. hash = temp->hash(); // by current thread, check if the displaced
  119. if (hash) { // header contains hash code
  120. return hash;
  121. }
  122. // WARNING:
  123. // The displaced header is strictly immutable.
  124. // It can NOT be changed in ANY cases. So we have
  125. // to inflate the header into heavyweight monitor
  126. // even the current thread owns the lock. The reason
  127. // is the BasicLock (stack slot) will be asynchronously
  128. // read by other threads during the inflate() function.
  129. // Any change to stack may not propagate to other threads
  130. // correctly.
  131. }
  132. // Inflate the monitor to set hash code
  133. monitor = ObjectSynchronizer::inflate(Self, obj, inflate_cause_hash_code);
  134. // Load displaced header and check it has hash code
  135. mark = monitor->header();
  136. assert(mark->is_neutral(), "invariant");
  137. hash = mark->hash();
  138. if (hash == 0) {
  139. hash = get_next_hash(Self, obj);
  140. temp = mark->copy_set_hash(hash); // merge hash code into header
  141. assert(temp->is_neutral(), "invariant");
  142. test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
  143. if (test != mark) {
  144. // The only update to the header in the monitor (outside GC)
  145. // is install the hash code. If someone add new usage of
  146. // displaced header, please update this code
  147. hash = test->hash();
  148. assert(test->is_neutral(), "invariant");
  149. assert(hash != 0, "Trivial unexpected object/monitor header usage.");
  150. }
  151. }
  152. // We finally get the hash
  153. return hash;
  154. }

2.Java Object.hashCode()返回的是对象内存地址?不是!

OpenJDK8 默认hashCode的计算方法是通过和当前线程有关的一个随机数+三个确定值,运用Marsaglia’s xorshift scheme随机数算法得到的一个随机数。和对象内存地址无关

  1. 当然也可以自己实现hashcode方法,关于hashcode() equals()。主要是利用hashcode 可以判断2个对象的**不等**,hashcode相等,对象不一定相等,但hashcode不等,可以肯定2个对象不相等。在很多地方判断对象等不等。如果equals 定义了2个对象是相等的,需要注意hashcode还是不是相等的。

3.String类的hasCode()

  1. public int hashCode() {
  2. int h = hash;
  3. if (h == 0 && value.length > 0) {
  4. char val[] = value;
  5. for (int i = 0; i < value.length; i++) {
  6. h = 31 * h + val[i];
  7. }
  8. hash = h;
  9. }
  10. return h;
  11. }

2.使用JOL查看对象信息

maven 依赖

  1. <dependency>
  2. <groupId>org.openjdk.jol</groupId>
  3. <artifactId>jol-core</artifactId>
  4. <version>0.9</version>
  5. </dependency>

为了内存比较“整齐”,关闭压缩指针,启动参数加上-XX:-UseCompressedOops

1.测试对象

  1. class AAA{
  2. private int number;
  3. }

2.测试方式1

  1. public static void main(String[] args) {
  2. AAA aaa = new AAA();
  3. System.out.println("---------before invoke hascode()-----------------");
  4. System.out.println(ClassLayout.parseInstance(aaa).toPrintable());
  5. /*invoke hashcode() 转换成16进制*/
  6. System.out.println(Integer.toHexString(aaa.hashCode()));
  7. System.out.println("------------after invoke hascode()-----------------");
  8. System.out.println(ClassLayout.parseInstance(aaa).toPrintable());
  9. synchronized (aaa){
  10. System.out.println("---------in synchronized() func--------------");
  11. System.out.println(Integer.toHexString(aaa.hashCode()));
  12. System.out.println(ClassLayout.parseInstance(aaa).toPrintable());
  13. System.out.println(Integer.toHexString(aaa.hashCode()));
  14. }
  15. System.out.println("---------after invoke synchronized()--------------");
  16. System.out.println(Integer.toHexString(aaa.hashCode()));
  17. System.out.println(ClassLayout.parseInstance(aaa).toPrintable());
  18. }

输出

  1. ---------before invoke hascode()-----------------
  2. AAA object internals:
  3. OFFSET SIZE TYPE DESCRIPTION VALUE
  4. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  5. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  6. 8 4 (object header) a8 35 85 1c (10101000 00110101 10000101 00011100) (478492072)
  7. 12 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  8. 16 4 int AAA.number 0
  9. 20 4 (loss due to the next object alignment)
  10. Instance size: 24 bytes
  11. Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  12. 7e0b37bc
  13. ------------after invoke hascode()-----------------
  14. AAA object internals:
  15. OFFSET SIZE TYPE DESCRIPTION VALUE
  16. 0 4 (object header) 01 bc 37 0b (00000001 10111100 00110111 00001011) (188201985)
  17. 4 4 (object header) 7e 00 00 00 (01111110 00000000 00000000 00000000) (126)
  18. 8 4 (object header) a8 35 85 1c (10101000 00110101 10000101 00011100) (478492072)
  19. 12 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  20. 16 4 int AAA.number 0
  21. 20 4 (loss due to the next object alignment)
  22. Instance size: 24 bytes
  23. Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  24. ---------in synchronized() func--------------
  25. 7e0b37bc
  26. AAA object internals:
  27. OFFSET SIZE TYPE DESCRIPTION VALUE
  28. 0 4 (object header) b0 f4 34 03 (10110000 11110100 00110100 00000011) (53802160)
  29. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  30. 8 4 (object header) a8 35 85 1c (10101000 00110101 10000101 00011100) (478492072)
  31. 12 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  32. 16 4 int AAA.number 0
  33. 20 4 (loss due to the next object alignment)
  34. Instance size: 24 bytes
  35. Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  36. 7e0b37bc
  37. ---------after invoke synchronized()--------------
  38. 7e0b37bc
  39. AAA object internals:
  40. OFFSET SIZE TYPE DESCRIPTION VALUE
  41. 0 4 (object header) 01 bc 37 0b (00000001 10111100 00110111 00001011) (188201985)
  42. 4 4 (object header) 7e 00 00 00 (01111110 00000000 00000000 00000000) (126)
  43. 8 4 (object header) a8 35 85 1c (10101000 00110101 10000101 00011100) (478492072)
  44. 12 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  45. 16 4 int AAA.number 0
  46. 20 4 (loss due to the next object alignment)
  47. Instance size: 24 bytes
  48. Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

可以看到,在调用一次 hashcode之后,就会在object header 中生成hashcode。注意区分大小端模式。
搜狗截图20191011144038.png

object header 在有锁的情况下会发生变化,但是不会改变hashcode的值。

为什么有锁的状态下,头部的hashcode会变。无锁后 又变回来了?

这是因为header会随着锁的状态发生变化。只有在无锁的情况下,才是这些字段。
unused:25 | identity_hashcode:31 | unused:1 | age:4 | biased_lock:1 | lock:2

另外,调用了一次hashcode 就会在栈帧中存在hashcode,但是与 偏向锁的字段发生冲突,因此jvm采用调用过hashcode的,不会存在偏向锁。为什么其它锁 可以呢?因为保存了指向栈中锁记录的指针,可以记录在里面。
搜狗截图20191011162436.png