Wednesday 11 May 2016

Thread.yield() method in java

A yielding thread tells the virtual machine that it’s willing to let other threads be scheduled in its place. This indicates that it’s not doing something too critical.

The java.lang.Thread.yield(),  a native method causes the currently executing thread object to temporarily pause and allow other threads to execute.

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 the discretion of the implementation.

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.


public static native void yield();


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

public class TestYield {
      public static void main(String...args){
            Thread thread1=new Thread(new ThreadClass1(),"t1");
            Thread thread2=new Thread(new ThreadClass2(),"t2");
            thread1.start();
            thread2.start();
      }
}

class ThreadClass1 implements Runnable {
      public void run(){
            for(int i=0;i<5;i++){
                Thread.yield();
                Print.print("i="+i+" ,Thread="+Thread.currentThread().getName());
            }         
      }
}

class ThreadClass2 implements Runnable {
      public void run(){
            for(int i=0;i<5;i++){
               Print.print("i="+i+" ,Thread="+Thread.currentThread().getName());
            }         
      }
}

class Print {
      public static void print(String string) {
            System.out.println(string);
      }
}

Output:
i=0 ,Thread=t2
i=0 ,Thread=t1
i=1 ,Thread=t2
i=1 ,Thread=t1
i=2 ,Thread=t2
i=2 ,Thread=t1
i=3 ,Thread=t2
i=3 ,Thread=t1
i=4 ,Thread=t2
i=4 ,Thread=t1

JDK 6 yield method performance is better to JDK 5

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.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...