Interview Questions

what is significance of yield() method, what state does it put thread in?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

28. what is significance of yield() method, what state does it put thread in?

yield() is a native method it’s implementation in java 6 has been changed as compared to its implementation java 5. As method is native it’s implementation is provided by JVM.

In java 5, yield() method internally used to call sleep() method giving all the other threads of same or higher priority to execute before yielded thread by leaving allocated CPU for time gap of 15 millisec.

But java 6, calling yield() method gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint. So, sometimes even after using yield() method, you may not notice any difference in output.

salient features of yield() method>

Definition : yield() method when called on thread gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint.

Thread state : when yield() method is called on thread it goes from running to runnable state, not in waiting state. Thread is eligible to run but not running and could be picked by scheduler at anytime.

Waiting time : yield() method stops thread for unpredictable time.

Static method : yield() is a static method, hence calling Thread.yield() causes currently executing thread to yield.

Native method : implementation of yield() method is provided by JVM.

Let’s see definition of yield() method as given in java.lang.Thread - public static native void yield();

synchronized block : thread need not to to acquire object lock before calling yield() method i.e. yield() method can be called from outside synchronized block.

(Continued on next question...)

Other Interview Questions