Wednesday, July 3, 2013

Threads: Difference between wait() and sleep()

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

I never delve into the world of threading, so I could not ever make a much difference between wait and sleep but after understanding the wait method, I could make out something.

Java doc

public final void wait() throws InterruptedException

Causes current thread to wait until another thread invokes the notify() method or the  notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAllmethod. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

What is sleep and wait
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.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(). Wait is called on an object, not a thread; we call this object the "lock object." Beforelock.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.


Example

Wait Example
public class ConnectionPool {
   private List<Connection> connections = createConnections();

   private List<Connection> createConnections() {
     List<Connection> conns = new ArrayList<Connection>(5);
     for (int i = 0; i < 5; i++) {
       ... add a Connection to conns
     }
     return conns;
   }
}

public Connection getConnection() throws InterruptedException {
   synchronized (connections) {
     while (connections.isEmpty()) {
       connections.wait();
     }
     return connections.remove(0);
   }
}

public void returnConnection(Connection conn) {
   synchronized (connections) {
     connections.add(conn);
     connections.notify();
   }
}

Sleep Example: Requirement is to copy files existed at server to local machine. This activity should be repeated in every 5 minutes.
                public void CopyFilesFromServerToLocal() throws InterruptedException {
                                performCopy();
                                sleep(5*60*1000);
}

Difference between Thread.sleep and Object.wait method

Thread.sleep
Object.wait
It is a static method. On calling the method, it will send current running thread in sleep status. T.sleep(1000) and sleep(1000) both will send current running thread to sleep status. ( T is an instance of another thread)
It is an instance method.
Thread does not uses any CPU cycle while sleeping
Thread does not use any CPU cycle while waiting.
Thread does not releases any lock it possesses
Releases the lock of the object on which wait was called. Other locked monitors will not be released by the waiting thread.
This method can be called from non-synchronized block.
This method must be called from synchronized block. Because if block is not synchronized, then no objects are locked.
Sleep is used for Time Synchronization.
It is used in inter-thread communication.
In Lehman terms sleep tells JVM that I’m done with my time-slice, and please don’t give me another one for at least n milliseconds.
In Lehman terms wait tells JVM that I’m done with my time-slice. Don’t give me another timeslice until someone calls notify().

No comments:

Post a Comment