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

 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.

Leave a Reply