Home  >  Article  >  Java  >  How Does Java Generate Hash Codes When `hashCode()` is Not Overridden?

How Does Java Generate Hash Codes When `hashCode()` is Not Overridden?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 21:17:02438browse

How Does Java Generate Hash Codes When `hashCode()` is Not Overridden?

Default Hash Code Behavior in Java

If the hashCode() method is not overridden, invoking it on an object in Java yields a system-generated hash code.

Underlying Mechanism

In HotSpot JVM, the hashCode is typically determined by one of the following methods:

  • Random Number (Default in Java 7): A random number is generated and stored in the object header. This default approach introduces the possibility of race conditions or delays in highly-concurrent environments.
  • Thread-Local Random Generator (Default in Java 8): A thread-local random generator is employed to avoid race conditions and improve performance.
  • Object Pointer: The object pointer is mixed with a random value to generate the hash code. However, this method can lead to poor hash table distribution.

Controllable Behavior

The behavior of the hash code generation can be modified using the -XX:hashCode=n HotSpot JVM option. The following values are available:

  • 0 (Default in Java 7): Global random generator
  • 5 (Default in Java 8): Thread-local xor-shift random generator
  • 1: Object pointer mixed with random value
  • 2: Always 1
  • 3: Autoincrementing numbers
  • 4: Object pointer trimmed to 32 bits

It's important to note that even when using the -XX:hashCode=4 option, the hash code may not always correspond to the object address due to potential object movement.

The above is the detailed content of How Does Java Generate Hash Codes When `hashCode()` is Not Overridden?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn