介绍
散列函数(英语:Hash function)又称散列算法、哈希函数,是一种从任何一种数据中创建小的数字“指纹”的方法。散列函数把消息或数据压缩成摘要,使得数据量变小,将数据的格式固定下来。
在Java中,每个Object都有一个hashCode方法,有需要可以进行重写。
Object类的hashCode
public native int hashCode();
可以看到此方法为native方法,底层是调用了C++的函数,因为是在Object类中,翻开JDK源码的Object.c的定义
#include <stdio.h>#include <signal.h>#include <limits.h>#include "jni.h"#include "jni_util.h"#include "jvm.h"#include "java_lang_Object.h"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},};JNIEXPORT void JNICALLJava_java_lang_Object_registerNatives(JNIEnv *env, jclass cls){(*env)->RegisterNatives(env, cls,methods, sizeof(methods)/sizeof(methods[0]));}JNIEXPORT jclass JNICALLJava_java_lang_Object_getClass(JNIEnv *env, jobject this){if (this == NULL) {JNU_ThrowNullPointerException(env, NULL);return 0;} else {return (*env)->GetObjectClass(env, this);}}
可以看到hashCode方法实际上调用的是JVM_IHashCode这个方法。查找这个方法发现在jvm.cpp中定义
// java.lang.Object ///////////////////////////////////////////////JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))JVMWrapper("JVM_IHashCode");// as implemented in the classic virtual machine; return 0 if object is NULLreturn handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;JVM_END
从这里看出JVM_IHashCode实际又是调用的ObjectSynchronizer::FastHashCode这个方法,继续查找到这个方法的定义在synchronizer.cpp中:
FastHashCode函数
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") ;// 是java线程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;// 读出一个稳定的mark,如果对象处于锁膨胀,那么等待锁膨胀完毕再读markOop mark = ReadStableMark (obj);// 判断没有处于偏向锁状态// object should remain ineligible for biased lockingassert (!mark->has_bias_pattern(), "invariant") ;// 处于无锁状态if (mark->is_neutral()) {hash = mark->hash(); // this is a normal header// 有hash值直接返回if (hash) { // if it has hash, just return itreturn hash;}// 没有hash值,调用get_next_hash函数计算hash值hash = get_next_hash(Self, obj); // allocate a new hash codetemp = mark->copy_set_hash(hash); // merge the hash code into header// use (machine word version) atomic operation to install the hashtest = (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 ownedassert (temp->is_neutral(), "invariant") ;hash = temp->hash(); // by current thread, check if the displacedif (hash) { // header contains hash codereturn 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 codemonitor = ObjectSynchronizer::inflate(Self, obj);// Load displaced header and check it has hash codemark = 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 headerassert (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 codehash = test->hash();assert (test->is_neutral(), "invariant") ;assert (hash != 0, "Trivial unexpected object/monitor header usage.");}}// We finally get the hashreturn hash;}
以上分析出在对象头没有hash值的情况下,会调用get_next_hash函数计算出hash值,get_next_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() ;} elseif (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 ;} elseif (hashCode == 2) {// 固定返回1value = 1 ; // for sensitivity testing} elseif (hashCode == 3) {// 序列自增value = ++GVars.hcSequence ;} elseif (hashCode == 4) {// 返回内存地址value = cast_from_oop<intptr_t>(obj) ;} else {// Marsaglia's xor-shift 随机数算法// 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;}
可以看到有6种hashCode的生成方法,根据hashCode变量指定不同的生成方案,可以通过在JVM启动参数中添加-XX:hashCode=?,改变默认的hashCode计算方式。
对于OpenJDK8,默认是用最后一种,使用的是Marsaglia’s xor-shift随机数算法。
product(intx, hashCode, 5,"(Unstable) select hashCode generation algorithm")
此方法使用了三个固定值和一个随机数,在thread.cpp中定义
// thread-specific hashCode stream generator state - Marsaglia shift-xor form_hashStateX = os::random() ;_hashStateY = 842502087 ;_hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ;_hashStateW = 273326509 ;
所以,对于JDK8,对象在没有重写hashCode的情况下,hashCode的生成和内存地址无关,默认是根据Marsaglia’s xor-shift算法随机生成的。
