Sobes.tech
Junior — Middle

Can the wait() method be used on an object without holding a synchronized lock?

sobes.tech AI

Answer from AI

No, the wait() method on an object in Java can only be called if the current thread owns the monitor of that object, meaning it is inside a synchronized block synchronized on that object. Calling wait() without holding the lock will throw an IllegalMonitorStateException.

Example of correct usage:

synchronized(obj) {
    obj.wait();
}

This is because wait() releases the monitor and puts the thread into a waiting state, and for proper operation, the monitor must be acquired.