Search code examples
javamultithreadingwaitillegalstateexceptionnotify

IllegalStateException with wait(),notify()


Right now ,i am preparing for java ocajp 8 certification and just looking through some dumps and it says that following code throws IllegalStateException;

and code is below` 

void waitForSignal() throws Exception{
    Object obj = new Object(); 
    synchronized (Thread.currentThread()) {
        obj.wait(); 
        obj.notify(); 
    } 
}` 

Preceding code is all it provided and nothing else ,why does a exception arise here and fact is i know little about multithreading. and according to java documentation

IllegalStateException : Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

So i suppose wait() or notify() is invoked at inappropriate time... if i am right why is it illegal time and if i am wrong ,then explain why exception arises..


Solution

  • You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

    synchronized (obj) {
    

    According to javadoc :

    public class IllegalMonitorStateException extends RuntimeException Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.