1

Though I have written wait inside synchronized block. I am getting IllegalMonitorStateException. What's the reason then?

package trials;

public class WaitNotifyTrial {

    public static void main(String[] args){
        Generator g=new Generator();
        g.start();
        System.out.println("Start");
        synchronized (g) {
                try {
                    g.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("Printing exception");
                    e.printStackTrace();
                }
                System.out.println(g.value);
        }
    }
}

class Generator extends Thread{

    int value;

    public void run(){
        synchronized (this) {
            value=10;
        }
        notify();
        }
    }
}
3
  • 2
    Are you sure your error is not from notify(); which is outside of synchronized(this) block. which means your thread doesn't possess monitor of Generator?
    – Pshemo
    Commented Jan 1, 2014 at 15:50
  • 2
    show the full stacktrace
    – stinepike
    Commented Jan 1, 2014 at 15:53
  • yes..was doing mistake..after putting notify() inside synchronized block,exception got resolved :) thanks :) Commented Jan 3, 2014 at 17:04

1 Answer 1

6

These are some of the things wrong with your code:

  • you call notify() outside of synchronized (this) (this is your immediate problem);
  • you don't use the proper wait-loop idiom, thus risking nondeterministic behavior/deadlocks in the face of spurious wakeups and missed notifications;
  • you use the wait-notify mechanism on a Thread instance, which is recommended against in its documentation;
  • you extend Thread instead of using that class as-is and only passing it an instance of your implementation of Runnable.

For almost a whole decade now, the general advice has been to avoid the wait-notify mechanism altogether and instead use one of synchronization aids from java.util.concurrent, such as the CountDownLatch.

4
  • can you elaborate regarding number 3? why is it bad to use wait \notify on thread instance?
    – axelrod
    Commented Jan 2, 2014 at 21:31
  • @axelrod I thought the link to the official documentation was enough. What piece of the puzzle are you still missing? Commented Jan 2, 2014 at 21:36
  • Not sure what could possibly break \ not work as expected if i'll use it this way
    – axelrod
    Commented Jan 2, 2014 at 21:39
  • 1
    All threads waiting on a thread instance will be notified when that thread ends. Also, each time notify is executed on that instance, all threads executing join on the thread will be notified. Neither of these may actually break anything in your code. However, since there is never any need to wait/notify on a thread instance, it is a non-issue to avoid it. Commented Jan 2, 2014 at 21:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.