0

I'm testing some java multithreading things, and I ran into this problem : I have a Thread that calls a method of Producer class and that method has a synchronized block locked on the object I passed in the constructor. App.class :

public class App {

    public static void main(String[] args) {
        Object lock = new Object();
        Producer producer = new Producer(lock);

        Thread producerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                producer.produce();
            }
        });

        producerThread.start();
        try {
            producerThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

Producer class :

public class Producer {

    private final Object lock;

    public Producer(Object lock) {
        this.lock = lock;
    }

    public void produce() {
        synchronized (lock) {
            System.out.println("Producer started ...");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Producer resumed");
        }
    }
}

And I get :

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.base/java.lang.Object.wait(Native Method)
    at java.base/java.lang.Object.wait(Object.java:328)
    at Producer.produce(Producer.java:13)
    at App$1.run(App.java:15)
    at java.base/java.lang.Thread.run(Thread.java:844)

Process finished with exit code 0

So, what happens when I pass a lock object through the constructor, and why its not working?

Danil.B
  • 880
  • 1
  • 11
  • 23

1 Answers1

2

That's because you call wait() not on lock object, but on this, while synchronizing on lock. Since you do not own monitor on this, IllegalMonitorStateException is thrown. So the fix is lock.wait()

But even with that fix your code will hang forever, because notify/notifyAll is never called.

gdomo
  • 1,650
  • 1
  • 9
  • 18
  • Thanks, that helped me. So, it means to stop the thread that currently has a lock I heve to call wait method of that lock. And notify will be called from another class, which uses the same lock object. – Danil.B Jul 26 '18 at 14:49