Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CountDownLatch: object not locked by thread before wait()

I want to pause the main thread until the other thread finishes.
I tried CountDownLatch and semaphore. but none of them worked. I got the same error for both.

Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 public void testCountDownLatch(){
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                countDownLatch.countDown();
                //Toast.makeText(MainActivity.this, "Latch Released", Toast.LENGTH_SHORT).show();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();

    try {
        countDownLatch.wait();
        Toast.makeText(this, "Yes! I am free now", Toast.LENGTH_SHORT).show();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

I tried to search for a few hours and was able to understand the cause of the error (wait() won’t know if the countdown() gets called before it, in that case it would wait forever) but I couldn’t able to understand how to fix it:(

>Solution :

You are using the wrong method. You should call await, not wait. See CountDownLatch for example code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading