Java 对象的哈希值是每次 hashCode() 方法调用重计算么?

对于没有覆盖hashCode()方法的对象

若是没有覆盖 hashCode() 方法,那么哈希值为底层 JDK C++ 源码实现,实例每次调用hashcode()方法,只有第一次计算哈希值,以后哈希值会存储在对象头的 标记字(MarkWord) 中。git

image

若是进入各类锁状态,那么会缓存在其余地方,通常是获取锁的线程里面存储,恢复无锁(即释放锁)会改回原有的哈希值github

对应源码synchronizer.cpp编程

//若是是无锁状态
if (mark.is_neutral()) {          
  hash = mark.hash();
  //若是hash不等于0,证实计算过,直接返回
  if (hash != 0) {              
    return hash;
  }
  //不然,计算hash值
  hash = get_next_hash(self, obj);  // get a new hash
  //拷贝到Header中记录
  temp = mark.copy_set_hash(hash); 
  test = obj->cas_set_mark(temp, mark);
  //可能有并发,并且不一样默认哈希值计算方法,可能每次哈希值不同,只有 CAS 成功的才是最后的哈希值
  //默认的哈希值计算,不论计算多少次,都不会变
  if (test == mark) {             
    return hash;
  }
} else if (mark.has_monitor()) {
  //若是是有 monitor 锁状态(重量级锁),则获取其 monitor,哈希值会记录在monitor的头部
  monitor = mark.monitor();
  temp = monitor->header();
  assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
  hash = temp.hash();
  if (hash != 0) {
    OrderAccess::loadload_for_IRIW();
    if (monitor->is_being_async_deflated()) {
      monitor->install_displaced_markword_in_object(obj);
      continue;
    }
    return hash;
  }
} else if (self->is_lock_owned((address)mark.locker())) {
  // 若是是轻量级锁状态,获取轻量锁,其中也记录着以前计算的哈希值
  temp = mark.displaced_mark_helper();
  assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
  hash = temp.hash();
  if (hash != 0) {                  // if it has a hash, just return it
    return hash;
  }
}

对于已经覆盖hashCode()方法的对象

对于已经覆盖hashCode()方法的对象,则每次都会从新调用hashCode()方法从新计算哈希值。缓存

微信搜索“个人编程喵”关注公众号,每日一刷,轻松提高技术,斩获各类offer:微信

image

相关文章
相关标签/搜索