-1

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} .

Chetan Gowda
  • 390
  • 6
  • 15

1 Answers1

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