MinhHoang
MinhHoang

Reputation: 711

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

Upvotes: 5

Views: 4760

Answers (3)

Daniel Trebbien
Daniel Trebbien

Reputation: 39208

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.

Upvotes: 6

Narendra Yadala
Narendra Yadala

Reputation: 9664

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.

Upvotes: 1

erickson
erickson

Reputation: 269717

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.

Upvotes: 1

Related Questions