Search code examples
javamultithreadingobject

Java wait0() native implementation source


I was looking into Object.wait for Java and found out that it internally calls a wait0() method. You can find it's declaration in openJdk here:

public final void wait(long timeoutMillis) throws InterruptedException {
    long comp = Blocker.begin();
    try {
        wait0(timeoutMillis);
    } catch (InterruptedException e) {
        Thread thread = Thread.currentThread();
        if (thread.isVirtual())
            thread.getAndClearInterrupt();
        throw e;
    } finally {
        Blocker.end(comp);
    }
}

// final modifier so method not in vtable
private final native void wait0(long timeoutMillis) throws InterruptedException;

Can anyone point out to me where is the implementation for this native wait0() method?


Solution

  • TL;DR: Where is it?

    The implementation can be found in objectMonitor.cpp.

    The path to wait0

    While the Java sources are stored in a directory called classes, native code is stored in the native directory. Specifically, you want the native/libjava directory containing native code for some core Java classes.

    In there, you can find a file called Object.c containing some native code for the Object class. However, that class doesn't seem to contain much useful stuff except including jvm.h.

    Thisheader file contains a JVM_MonitorWait function declaration and its implementation can be found in jvm.cpp.

    Most importantly, that function calls ObjectSynchronizer::wait which is in turn declared in a file called synchronizer.hpp. In the same directory, you can find a file called synchronizer.cpp containing the implementation which calls ObjectMonitor::wait.

    Finally, you can find the code of ObjectMonitor::wait in objectMonitor.cpp.

    How to navigate

    IDE

    The best way to find what you are looking for in a codebase like this is to clone the project and set it up in an IDE that can search the methods for you. However, setting up a project like the JDK in an IDE and building it can be tedious and might take a while.

    with a browser

    You can also navigate through the repository in your browser by looking for files with names similar to what you are looking for (e.g. using GitHub's Go To File feature).

    However, in some cases, you might want to use some sort of full text search. In cases like that, you could try GitHub Codespaces or the GitHub Code search as outlined here. For doing this, you navigate to https://github.com/search, enter repo: followed by the repository name (including user/org, in this case repo:openjdk/jdk) as well as the text you want to search. Then, you can switch to the code search for the given term.