When waiting and notifying on an object 'x' assume x.wait() and x.notify() . Should the calls to wait and notify be also synchronized on the same object ? I mean synchronized(x){x.wait} , or is it ok/sensible/wrong to use another object for synchronization I mean synchronized(y){x.wait} .
Asked
Active
Viewed 52 times
-1
-
2synchronized(y){x.wait} won't work. You can try it. – Andrey Cheboksarov Jun 23 '17 at 12:47
1 Answers
2
Should the calls to wait and notify be also synchronized on the same object?
Not only should they be synchronized on the same object, they must be synchronized on the same object.
In fact, the documentation of wait and notify is quite clear on what will happen if code doesn’t follow that rule:
Throws:
IllegalMonitorStateException
- if the current thread is not the owner of this object's monitor.

VGR
- 40,506
- 4
- 48
- 63