Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDK implementation of Thread.join()

I was wondering how Java implements the join() method to wait for a thread to finish. According to the source code:

public final synchronized void  [More ...] join(long millis)
throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
            wait(0);
        }

    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

The calling thread obtains the running thread's monitor and wait() at line 1160 indefinitely while running thread is still alive.

My question is: where is (and who calls) the notify() or notifyAll() when the thread completes, so that it wakes up the calling thread?

To be perfectly clear, the question is about where in the JDK/JVM is notify() called, not in our code.

Thank you.

like image 436
PoweredByRice Avatar asked Mar 19 '14 03:03

PoweredByRice


1 Answers

notifyAll (or its native equivalent) is called in ensure_join in src/share/vm/runtime/thread.cpp, at line 1526 in the current version, which is called from JavaThread::exit in the same file.

like image 120
Peter G Avatar answered Oct 05 '22 23:10

Peter G