314314314 314314314 -4 years ago 159
Java Question

When a Java thread performs a potentially blocking action, does it always loss the current CPU timeslice?

A potentially blocking action (e.g. Thread.join(), obj.wait(), monitorEnter ), may continue to execute under some circumstances (e.g. For Thread.join(), if the interrupt flag is set by the time of calling, the method won't block. For obj.wait(), if the interrupt flag is set and monitor is available, the action won't block). Under these circumstances, will the java thread continue in the current CPU timeslice; or will it release the current timeslice and wait for next dispatch?

Answer Source

Your question is a little confused - a thread can only call wait if it already owns the monitor. Which is acquired by entering a synchronised block and going through the monitorEnter process.

But to try and answer your question: if a thread invokes a potentially blocking action (i.e, needs to acquire the object monitor), will it always lose the timeslice? The answer is no. It will try a couple of "fast path" attempts first, and only then will it park the thread.

The code for monitor synchronisation is here: http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/share/vm/runtime/synchronizer.cpp#l1192

The VM first tries a very quick atomic CAS operation to get the monitor. If that fails it tries a short spinlock (to hold the CPU). If the spinlock fails then it parks the thread.

The park happens here under Windows: http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/os/windows/vm/os_windows.cpp#l4787

where it looks like it calls the Windows WaitForSingleObject API function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download