Wednesday, August 8, 2012

Difference between yield and wait method in Java

Yield vs wait in Java
Yield and wait method in Java, though both are related to Thread,  are completely different to each other. Main difference between wait and yield in Java is that wait is used for flow control and inter thread communication while yield is used just to relinquish CPU to offer an opportunity to another thread for running. In this Java tutorial we will what are differences between wait and yield method in Java and when to use wait() and yield(). What is important for a Java programmer is not only understand difference between wait() and yield() method but also know implications using yield method. If your program is depends upon yield method for performance or correctness than its most likely not work perfectly on all platforms because of platform dependent nature of yield method which we will see in this Java article along with wait vs yield comparison.

Difference between wait and yield method in Java

Difference between wait and yield in Java

Here is a list of differences between Yield and wait method in Java, good to remember for Java interviews :

1) First difference between wait vs yield method is that, wait() is declared in java.lang.Object class while Yield is declared on java.lang.Thread class.

2) Second difference between wait and yield in Java is that wait is overloaded method and has two version of wait, normal and timed wait while yield is not overloaded.

3) Third difference between wait and yield is that wait is an instance method while yield is an static method and work on current thread.

4) Another difference on wait and yield is that When a Thread call wait it releases the monitor.

5) Fifth difference between yield vs wait which is quite important as well is that wait() method must be called from either synchronized block or synchronized method, There is no such requirement for Yield method.

6) Another Java best practice which differentiate wait and yield is that, its advised to call wait method inside loop but yield is better to be called outside of loop.

That's all on difference between wait and yield method in Java. In summary wait and yield are completely different and there for different purpose. Use wait for inter thread communication while yield is not just reliable enough even for the mentioned task. prefer Thread.sleep(1) instead of yield.

2 comments:

  1. Did you thought about using busy spinning instead of yield or wait, as part of your wait strategy in Java multithreading? Can you please list down some advantage and disadvantage of using busy spinning over yied or wait() method?

    ReplyDelete

Java67 Headline Animator