leventov leventov - 4 months ago 8
Java Question

Does calling object.notifyAll() cause lock rebiasing/inflation in Hotspot JVM?

When I call

object.notifyAll()
on a completely uncontented (possibly biased, if this is allowed for the current JVM) monitor, in particular if no threads are actually waiting on the monitor, does it cause monitor rebiasing and/or inflation?

Answer

It causes biased lock revocation (biased -> thin state transfer) only.

Referring to hotspot source code (synchronizer.cpp):

void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
    if (UseBiasedLocking) {
       BiasedLocking::revoke_and_rebias(obj, false, THREAD);
       assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
    }

    markOop mark = obj->mark();
    if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
        return;
    }
    ObjectSynchronizer::inflate(THREAD,
                          obj(),
                          inflate_cause_notify)->notifyAll(THREAD);
}

Caller checks if lock is biased (and revokes it if necessary), then checks mark->has_locker() (it's the same as "is monitor thin"). If so, then its wait-set is empty and fast-exit is performed without any inflation or other effects (is_lock_owned_check performed only to throw IllegalMonitorStateException in case of illegal usages).

Also note, that in Java 9 entry point for notify is quick_notify as part of JEP 143: Improve Contended Locking, but it performs same checks anyway.