Wednesday, June 17, 2015

What happens when Object.wait() is called?

Quite a long wait!

Oxford Dictionary defines wait and sleep as below:
wait: delay action until (someone) arrives or is ready.

What happens when Object.wait() is called from inside the synchronized block? MULTI-THREAD SYNCHRONIZATION

  1. The running Thread is switched out (context switching) and goes to the WAITING state .  In WAITING state, itrequires no CPU time-slice.
  2. In Java every Object is associated with two queues, wait queue and entry queue. Post Object.wait() Thread waits on the wait queue of the object.
  3. The Thread will hold no lock on the monitor object. Any other thread can enter the synchronized block.
  4. It will remain in WAITING state until some other Thread which will synchronize on the same object, calls Object.notify()
  5. Once Object.notify() is called, of all Threads that are WAITING on the same monitor object, one is awakened at random and is moved to BLOCKED state (Moved from waiting queue of object to entry queue of the object), where it tries to get the lock on monitor object. It has to fight with other Threads BLOCKED on the same Object. Once it gets the lock, it is scheduled to be executed by the CPU, again with no guarantees when.
  6. If 10 Threads have called Object.wait() on the same object, Object.notifyAll(), awakens all 10 threads and move them in BLOCKED state where they fight with other BLOCKED Threads for the lock on the object  One of these 10 might get the lock (some other Thread which was BLOCKED to enter the  synchronized block, might just get the lock) and rest 9 go back to the WAITING state (in effect waiting Queue of the Object) till they get the next notify signal.
  7. In BLOCKED state Thread incurs CPU cost as it tries to get the lock. JVM might try to get to acquire monitor lock multiple times before context switching it OR JVM might context switch it just after one try. It depends on Algorithm implemented at JVM level.

No comments:

Post a Comment