Friday, October 17, 2008

Notes on wait method

  • the wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run
  • the wait() method is defined in the Object class
  • wait() can only be invoked from within synchronized code
  • it should always be wrapped in a try block as it throws IOExceptions
  • there are actually three wait() methods
    1. wait()
    2. wait(long timeout)
    3. wait(long timeout, int nanos)
  • the timeout is measured in milliseconds
  • nanos is measured in nanoseconds
  • wait() can only invoked by the thread that own's the lock on the object
  • when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur:
    1. another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread
    2. another thread invokes the notifyAll() method for this object
    3. another thread interrupts this thread
    4. the specified wait() time elapses
  • when one of the above occurs, the thread becomes re-available to the Thread scheduler and competes for a lock on the object
  • once it regains the lock on the object, everything resumes as if no suspension had occurred
  • if the thread was interrupted by another thread, an InterruptedException is thrown BUT not until after the thread regains it's lock on the object
  • the wait() method throws three exceptions
    1. IllegalArgumentException - if the timeout value passed is invalid
    2. IllegalMonitorStateException - if the current thread does not own the object's lock
    3. InterruptedException - if another thread interrupts the current thread. The interrupted status of the current thread is cleared
    Courtesy: http://www.janeg.ca/scjp/threads/wait.html

No comments: