5

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};
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
MinhHoang
  • 681
  • 3
  • 9
  • 22
  • Can you please clarify the question a bit more? What did you invoke notifyAll() on? Was it on the list object? – secreteyes Sep 21 '11 at 18:08
  • possible duplicate of [Why must wait() always be in synchronized block](http://stackoverflow.com/questions/2779484/why-must-wait-always-be-in-synchronized-block) –  Jul 06 '15 at 13:57

3 Answers3

6

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.

Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
1

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.

erickson
  • 265,237
  • 58
  • 395
  • 493
1

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.

Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43