Wednesday, June 17, 2015

What happens when Thread.sleep() is called?

Sleep well!

Oxford Dictionary defines sleep as below:
sleep: a condition of body and mind which typically recurs for several hours every night, in which the nervous system is relatively inactive and consciousness practically suspended

What happens when Thread.sleep(TIMEOUT) is called? TIME-SYNCHRONIZATION

  1. The running Thread is forcefully switched out (context switching) and put in TIMED_WAITING state for the specified interval.
  2. As name suggests, it simply sleeps and require no CPU time-slice. Theoretically speaking, if this is the only process running and you put Sleep statements with substantial TIMEOUT, you will notice drop in CPU usage. Short bursts of continuous sleep statements, might increase CPU usage as Context Switching incurs its own cost.
  3. Once the Sleep time is over, Thread is scheduled back to be executed. However there is no guarantee that  Context Switching will happen immediately. Depends upon the resources available. If a high priority work is going on, this Thread will not get CPU time instantaneously. If will be scheduled no doubt, but when it will be executed comes with no guarantee.
  4. Sleep can be interrupted by Thread.interrupt(). This caused InterruptedException to be thrown. It is normally used to HALT the operations.
  5. If sleep is called from a synchronized block (say). No other Thread can enter this block. Thread holds the ownership (lock) of the monitor object.
  6. sleep is a static method. If we call diffThread.sleep from the current Thread, it wont halt diffThread. It is the current Thread which will sleep.

No comments:

Post a Comment