jeudi 26 mars 2015

Why does Object.hashCode() return the same value across runs

So the default implementation of hashCode() on HotSpot returns a random value and stores it in the object header. This doesn't seem to have changed in Java 8 where the hash value is calculated by a call to os::random():



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
...


What I'm wondering is why hashCode() always returns the same value, also after shutting down the JVM which I tried by executing the simple test below, restarting my machine and then running main() again.



public class SimpleTest {
public static void main(String[] args) {
Object obj = new Object();
System.out.println(obj);
}
}


How can the output be the same everytime if hashCode() is actually os::random()?


Thanks a lot in advance.




java -version gives



java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)




Aucun commentaire:

Enregistrer un commentaire