Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait(), notify() and notifyAll() inside synchronized statement

I get following error when trying to do invoke notifyAll() inside a synchronized statement: Invoked Object.notify() outside synchronized context.

Example:

final List list = new ArrayList();
synchronized(list) {..... invoked notifyAll() here};
like image 802
MinhHoang Avatar asked Sep 21 '11 18:09

MinhHoang


3 Answers

You can only call wait(), notify(), and notifyAll() on the object that is being synchronized on:

synchronized (list) {
    //...
    list.notifyAll();
}

In other words, the calling thread must own the object's monitor.

If, inside synchronized (list), you call notifyAll(), you are actually calling notifyAll() on this rather than list.

like image 178
Daniel Trebbien Avatar answered Nov 02 '22 11:11

Daniel Trebbien


My guess is that you are calling notifyAll() on a different object, one for which you don't hold a lock. In your example, you may call notifyAll() on list, but not on this.

like image 28
erickson Avatar answered Nov 02 '22 09:11

erickson


A thread must own the lock on the object it's invoking wait, notify, notifyAll on. In the code you posted, the thread owns the lock on 'list' and then it calls notifyAll on 'this' object.

like image 31
Narendra Yadala Avatar answered Nov 02 '22 10:11

Narendra Yadala