The Object Class provides us with methods used interface with the Monitor-Based Synchronisation construct!
And as we know, all Classes in Java extend from the Object Class.
This ensures that just like Intrinsic Locks, the methods used for Monitor-Based Synchronisation is available to all Classes & objects!!
Diagram on thread states with regards to ObjectMonitors
Object Monitor Methods
Key Requirements
- All five methods throw
IllegalMonitorStateExceptionif called without holding the object’s monitor lock - Must be called inside a synchronized block/method on the specific object
- The calling thread must own the monitor of the object on which these methods are called
Object.wait()
- Releases the monitor lock and puts the thread in WAITING state
- Thread stays suspended until another thread calls
notify()ornotifyAll()on the same object - Must reacquire the lock before returning
- Can throw
InterruptedException
Object.wait(long timeout)
- Same as
wait()but with a timeout in milliseconds - Thread enters TIMED_WAITING state
- Automatically wakes up after timeout expires (even if not notified)
- Returns when notified, interrupted, or timeout occurs
Object.notify()
- Wakes up one arbitrary thread waiting on this object’s monitor
- The awakened thread must still reacquire the lock before proceeding
- If multiple threads are waiting, which one wakes up is not guaranteed
- Does nothing if no threads are waiting
- Does not release the lock
Object.notifyAll()
- Wakes up all threads waiting on this object’s monitor
- All awakened threads compete to reacquire the lock
- Generally safer than
notify()to avoid missed signals - Preferred when multiple threads might be waiting for different conditions
- Does not release the lock