2015-03-01

Java: Why is Object.wait() always Runnable?

In the Java thread dumps you see some parking threads that say: "java.lang.Thread.State: RUNNABLE", but obviously they are waiting for a monitor, so it should be "timed_wait" or "waiting".
Also, it says they are in a native frame.
How?
  1. Basically, all frames that are in native code, are Runnable. The jvm just doesn't care, and also can't check what the state is. So it will always be Runnable if the frame is native.
  2. When you call the Object.wait() through any kind of consequences, it will simply call Object.wait(0).
  3. However, Object.wait(timeout) is a native call to a JVM-internal function. (Hence the default threadstate.)
  4. Upon checking the source in the OpenJDK site, we find it simply routes the call to a function called JVM_MonitorWait, which is defined in jvm.cpp.
  5. This function eventually calls ObjectSynchronizer::wait([obj], [timeout], [traps]). This wait creates an object monitor based on the passed object reference. Then, the ObjectMonitor's wait method is called. (Note: sources linked for Linux target)
  6. This ObjectMonitor::wait manages the waiting queue. Calls park() on the current thread.
  7. In fact, park() is a member of os::PlatformEvent, so we need to go further.
  8. os::PlatformEvent:park() does an old-fashioned looped lock checking with pthread_cond_wait.