1

In the following snippet

synchronized(myMonitorObject)
  try{
    myMonitorObject.wait();
  } catch(InterruptedException e){...}
}

if the first line is omitted why the compiler does not object but instead IllegalMonitorStateException is thrown?

  • 4
    Because the monitor can be acquired outside of current file. Moreover, it can be acquired indirectly by calling some outside procedure. Compiler cannot detect all situations correctly. Therefore, the check is made in run time. – yeputons Jun 14 '17 at 13:39
  • 1
    Possible duplicate of [IllegalMonitorStateException on wait() call](https://stackoverflow.com/questions/1537116/illegalmonitorstateexception-on-wait-call) – VivekRatanSinha Jun 14 '17 at 13:43

1 Answers1

1

Consider the following example:

public void m1(Object lock) throws InterruptedException {
    lock.wait();
}

Should that be a compilation error?

Now consider this:

public void m2() throws InterruptedException {
    Object lock = new Object();
    synchronized (lock) {
        m1(lock);
    }
}

Should m1 still be a compilation error?

The problem with making m1 a compilation error (as you seems to be suggesting) is that what it is doing is not necessarily incorrect. In fact, it is impossible to for the compiler to reliably distinguish correct from incorrect without being conservative. The analogies are:

  • The compiler does not treat code that will trigger an NPE as a compilation error.
  • The compiler does treat the use of an uninitialized local variable as an error. However, Java's strict definite assignment rules mean that some cases where a variable would actually be initialized are treated as errors.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216