Reputation: 259
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?
Upvotes: 0
Views: 211
Reputation: 13525
if anotherThread.join()
is executed, and anotherThread
has finished, there will be no loss of CPU timeslice. Similary, if monitorEnter obj
is executed, and obj
is not locked, execution will continue without interruption.
If you deliberately want to release the current timeslice and wait for next dispatch, then call to Thread.yield()
or Thread.sleep(0)
, but JVM implementation may ignore your hint.
Upvotes: 0
Reputation: 1032
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.
Upvotes: 1
Reputation: 533492
There is no guarantee it will lose the CPU, nor that it will be blocked for a whole time slice if;
How this exactly work depends mostly on the OS. The busy waiting strategy is sometimes implemented in Java, in which case you will see it in the source code.
Upvotes: 1