TheLogicGuy
TheLogicGuy

Reputation: 690

Why do I get IllegalMonitorException in a synchronized block?

public static void main(String[] args) {
        String resource1 = "ratan jaiswal";
        Thread t1 = new Thread() {
            public void run() {
                synchronized (resource1) {
                    System.out.println("Thread 1: locked resource 1");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread t2 = new Thread() {
            public void run() {
                synchronized (resource1) {
                    System.out.println("Thread 2: locked resource 2");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
            }
        };

        t1.start();
        t2.start();
    }

After I run this code I get line 16 is the line with the wait() call

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at ThreadSyncFromMark.deadlock.dead$1.run(dead.java:16)

Why I get this exception as I see everything is OK here because t1 owns the monitor of resource1 when it call wait

Upvotes: 0

Views: 107

Answers (1)

Kayaman
Kayaman

Reputation: 73558

Why I get this exception as I see everything is OK here because t1 owns the monitor of resource1 when it call wait

Yes, t1 owns the monitor of resource1. But you're not calling resource1.wait(), you're calling this.wait().

You need to synchronize, wait() and notify() all on the same object (monitor) to make things work the way they should.

Upvotes: 4

Related Questions