Why is it programmer has to explicitly synchronize on the object monitor before calling object.wait or object.notify? Instead by definition both the methods in java.lang.Object could have been a synchronized method. Could someone explain the logic behind this?
Asked
Active
Viewed 42 times
0
-
That answer doesn't at all give the right reasons, which are much deeper. The whole wait-notify idiom would be broken if you put `synchronized` only around the actual method call: you must check the condition on which you are waiting while still holding the lock. Only that way can several threads enter the waiting state, and later wake up from it, in a thread-safe manner. – Marko Topolnik Jan 13 '14 at 09:04
-
A similar argument holds on the notifying side: to prevent race conditions with the waiting threads, you must both update the condition and then call `notify` within the same `synchronized` block. – Marko Topolnik Jan 13 '14 at 09:06
-
BTW anyone asking your question should also ask why the requirement to hold the lock in the first place---and the answer is again the one I gave above. – Marko Topolnik Jan 13 '14 at 09:10