For objects that do not override the hashCode() method

If the hashCode() method is not overridden, the hash is implemented as the underlying JDK C++ source code, and the instance calls the hashCode() method only the first time, after which the hash value is stored in the MarkWord in the object’s header.

If you enter various lock states, it will be cached elsewhere, usually in the thread that acquired the lock, and restoring no lock (i.e. releasing the lock) will be changed back to the original hash value.

Synchronizer.cpp:

If (mark.is_neutral()) {hash = mark.hash(); // If (mark.is_neutral()) {hash = mark.hash(); // If hash is not equal to 0, prove that it has been calculated, return if (hash! = 0) { return hash; } // Otherwise, compute the hash value hash = get_next_hash(self, obj); Temp = mark.copy_set_hash(hash); temp = mark.copy_set_hash(hash); test = obj->cas_set_mark(temp, mark); // If (test == mark) {return hash; // If (test == mark) {return hash; }} else if (mark.has_monitor()) {// If (mark.has_monitor()) {// If (mark.has_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(); 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; }}Copy the code

For objects that have overridden the hashCode() method

For objects that have already overridden the hashCode() method, the hashCode() method is called again each time to recalculate the hash value.

Wechat search “my programming meow” public account, a daily brush, easy to improve skills, won a variety of offers