Search code examples
javalockingwaitfinalizernotify

java: wait(), notify() and synchronized blocks


I learned that calling an Object's wait() method will release the object monitor, if present.

But I have some questions regarding calling notify() on this object by another thread:

  1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?

  2. will the waiting thread wake up, if a 3rd thread called wait() on this object?

  3. is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)

  4. What's happening if wait() will be called in the finalize() method?


Solution

    1. notify will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
    2. No guarantees. Call notifyAll to give all threads a chance to wake.
    3. Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
    4. This is probably a bad idea. Can you come up with a situation where this is necessary?