0

I do realize that this topic has been discussed at many places. But all of them talk about it's usage in multi-threaded environment.

In this following example, why is notify() supposed to be surrounded by synchronized? It goes in vain when the keyword is used, which it is supposed to do. But why the exception, java.lang.IllegalMonitorStateException, when it is not used?

public class HelloWorld {
   public static void main(String[] args) {
      ABC c = new ABC();
      c.put(0);
   }
}
class ABC {
   public synchronized void put(int value) {    // why synchronized now!
      System.out.println("Put: " + value);
      notify();
   }
}
Shashwat
  • 2,538
  • 7
  • 37
  • 56

1 Answers1

0

You supposed to use synchronized is because the lock is re-entrant, meaning that it can be acquired multiple times by the same thread. In other words if your thread already holds the lock on an object it doesn't have to wait on itself.

Abdelhak
  • 8,299
  • 4
  • 22
  • 36