Saturday 8 October 2016

Yield Vs Join and Sleep Vs Wait

In this post, I am going to discuss about some of the important methods of Thread class and their usage.These methods are also actively asked in interviews.There is very little chance that you would have had the experience of actually using them at the starting level.It is expected from all the interviewee to have basic idea about these methods. Before diving straight into the topic, first let us gather some background information which will help us to understand them better.

Understanding thread priorities and thread scheduling

JVM is a preemptive, priority-based scheduler for threads.Each java thread has a well defined priority.A developer can change the priority of the thread as per the requirements.If the user doesn't set the priority of the thread, a default priority is set for each thread which is same for all in a particular java application.This priority value has its significance in multi threaded environment. It helps the JVM to decide which thread to execute when more than one threads are waiting for a common resource.This is why it is called priority based scheduler. The operating system generally chooses the thread with the highest priority. If any high priority thread is ready for the execution then the scheduler interrupts (preempts) the low priority thread. However, there is a catch, the OS may choose to wait the high priority thread and continue wit the lower priority thread(Ya ya... I know, OS some time can be moody -_- ).

  • Remember that all the threads carry normal priority when a priority is not specified.
  • Priorities can be specified from 1 to 10. 10 being the highest, 1 being the lowest priority and 5 being the normal priority.
  • Remember that the thread with highest priority will be given preference in execution. But there is no guarantee that it will be in running state the moment it starts.
  • It can be assumed that the currently executing thread might have the higher priority when compared to the threads in the pool who are waiting for their chance. However as we have learned this is not 100% guaranteed.
  • It is the thread scheduler which decides what thread should be executed.
  • setPriority(Thread.MIN_PRIORITY) method can be used to set the priority of the thread.
  • Remember that the priorities should be set before the threads start method is invoked.
  • Thread class provides some predefined constants for setting the priority, MIN_PRIORITY,MAX_PRIORITY and NORM_PRIORITY.

sleep() is a method which is used to hold the process for the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.


yield() is defined as following in Thread.java.

/**
  * A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore
  * this hint. Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilize a CPU.
  * Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
  */

public static native void yield();

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. Note that it’s only a hint, though, and not guaranteed to have any effect at all.

join() method

The join() method of a Thread instance can be used to “join” the start of a thread’s execution to the end of another thread’s execution so that a thread will not start running until another thread has ended. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing.


Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout. When the timeout is reached, the main thread and taskThread are equally probable candidates to execute. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

Like sleep, join responds to an interrupt by exiting with an InterruptedException.

1 comment:

  1. I'm hoping you keep writing like this. I love how careful and in depth you go on this topic. Keep up the great work
    Best Sleep Apnea Treat | sleep apnea and headach

    ReplyDelete