0

I can't understand why I am getting an IllegalMonitorStateException on notifyAll in the following code. If I look in jconsole, I see the synchronized block in wakeUp() DOES own the lock. This is expected as wait() in printMessage will give up the lock by definition.

Anyone have any ideas?

public class Test {

private Long elapsedMillis=0l;

public void printMessage() {

    synchronized(elapsedMillis) {
       while(elapsedMillis == 0) {
            System.out.println("Pausing inside print message");
            try {
                elapsedMillis.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("printMessage: "+elapsedMillis);
}

public void wakeUp() {

    synchronized(elapsedMillis) {
        System.out.println("Inside wake up synchronized block");
        elapsedMillis = 99999999l;
        System.out.println("Set elapsed time and notifying");
        System.out.println("value inside wakeup "+elapsedMillis);
        elapsedMillis.notifyAll();
    }
}

public static void main(String[] args) throws InterruptedException {

    final Test test = new Test();

    Thread printThread = new Thread() {
        public void run() {
            test.printMessage();
        }
    };

    Thread wakeupThread = new Thread() {
        public void run() {
            test.wakeUp();
        }
    };

    printThread.setName("printThread");
    wakeupThread.setName("wakeupThread");

    printThread.start();
    Thread.sleep(5000);
    wakeupThread.start();
}

}

java.lang.IllegalMonitorStateException at java.lang.Object.notifyAll(Native Method)

JvmSd121
  • 351
  • 3
  • 17

0 Answers0