educative.io

How to avoid the exception

class Demonstration {
public static void main( String args[] ) throws InterruptedException {
IncorrectSynchronization.runExample();
}
}

class IncorrectSynchronization {

Boolean flag = new Boolean(true);

public void example() throws InterruptedException {

    Thread t1 = new Thread(new Runnable() {

        public void run() {
            synchronized (flag) {
                try {
                    while (flag) {
                        System.out.println("First thread about to sleep");
                        Thread.sleep(5000);
                        System.out.println("Woke up and about to invoke wait()");
                        flag.wait();
                    }
                } catch (InterruptedException ie) {

                }
            }
        }
    });

    Thread t2 = new Thread(new Runnable() {

        public void run() {
            flag = false;
            System.out.println("Boolean assignment done.");
        }
    });

    t1.start();
    Thread.sleep(1000);
    t2.start();
    t1.join();
    t2.join();
}

public static void runExample() throws InterruptedException {
    IncorrectSynchronization incorrectSynchronization = new IncorrectSynchronization();
    incorrectSynchronization.example();
}

}

How to to avoid the [IllegalMonitorStateException]
Once a thead sleeps it wont releases the lock. Then how come the second thread got the access to the flag?

Removing flag.wait() seems to avoid the exception.

I think this might be the reason:
the exception is thrown when you invoke these methods on an instance of Condition class without acquiring the associated lock with the condition.
These methods refers to wait() and notify(). You can read more on this point in this lesson.