I thought I would understand the concept of concurrency in Java, but now there is one thing which breaks my understanding:
Why do I have to enclose calls to wait() and notify() methods in synchronized blocks?
Assuming I have two threads: Thread A and Thread B. Also I have an object which I will use as a lock.
Now at some point in time, Thread A calls wait()
on the object and is blocked afterwards until some other thread calls notify()
on the same object. This was my understanding so far and this is fine. But now it sais that I need to enclose those calls in blocks synchronized on this object - indeed, I get an IllegalMonitorStateException
if I do not do this. If I add these blocks, it works fine - but why??
I would have expected, that if I use these synchronized blocks, then Thread A will keep the lock on the object forever, because the wait()
method keeps on running and Thread B just could not execute notify()
, because it could not acquire the lock on the object, as it is still owned by thread A.
However, as I said, in reality it works fine, Thread B can execute notify()
which unblocks Thread A ... Can someone please explain me exactly what happens here? How can Thread B acquire the lock?