Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IllegalMonitorStateException

When running our program we get an exception of type java.lang.IllegalMonitorStateException. On Java6 API website, it says there is a constructor that gives a details about the exception: IllegalMonitorStateException(String s)

How can we use this to get a better idea of where the bug is in our code? Is there anything else we can do (besides lots of debugging which we're currently doing) to pinpoint the function or line that failed?

like image 888
BeefCake__beefcake Avatar asked Dec 04 '09 23:12

BeefCake__beefcake


3 Answers

The details must be given when the Exception is created (Constructor, right?) and if you are not creating it, there is no way for you to provide the details.

You can analize the StackTrace of the Exception. It shows the classes, methods and souce line which were called to cause the Exception.

One cause for the IllegalMonitorStateException is trying to wait on an Object without having synchronized on it. See the Javadoc.

There are other possible causes and the Exception may be thrown by some library/external code. I think only the StackTrace can help...

like image 182
user85421 Avatar answered Nov 15 '22 21:11

user85421


This is maybe occurring because the instance of the object which you are calling wait or notify on is different that the instance you synchronized with. For example:

Integer      a;

a = new Integer(0);    

synchronized(a) {
    System.out.printf("I synchronized on %h.", a);
    ++a;
    System.out.printf("But, I am calling notify for %h and I hold no lock for it.", a);
    a.notify();
}

This will throw the IllegalMonitorStateException because the instance that 'a' points to is no longer the same.

like image 36
kmcguire Avatar answered Nov 15 '22 22:11

kmcguire


How can we use this to get a better idea of where the bug is in our code? Is there anything else we can do (besides lots of debugging which we're currently doing) to pinpoint the function or line that failed?

In this case, printing the message by itself probably won't help much. What you need is a stacktrace with source file names and line numbers.

  1. Make sure that all relevant ".class" files / JARs were built with file and line number debug information included. This is the default, but compiling with "-g:none" will strip this ... as will most JAR file obfuscators.

  2. Next, add a try / catch block to catch the IllegalMonitorStateException and either call ex.printStackTrace() or log the exception.

From the stacktrace you should be able to see what line in the code threw the exception. The chances are that is was a call to Object.wait(...) or something like that. Check the javadoc for the offending method to find out what circumstances cause the exception to be thrown.

(And once you are done, remember to move the try / catch block you added.)

like image 23
Stephen C Avatar answered Nov 15 '22 22:11

Stephen C