await() - "Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
If the current count is zero then this method returns immediately.
If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen:
The count reaches zero due to invocations of the countDown method; or
Some other thread interrupts the current thread.
If the current thread:
has its interrupted status set on entry to this method; or
is interrupted while waiting,
then InterruptedException is thrown and the current thread's interrupted status is cleared."
countDown() - "Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
If the current count is greater than zero then it is decremented. If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes.
If the current count equals zero then nothing happens."
Even when I run the code in main, it just waits, nothing happens. Yet having the code like below it verifies.
It doesn't make sense. Why call the await method, which will basically make the thread wait endlessly (because the countdown() is not called or the thread is not interrupted) ?
I don't understand the point they are trying to make.
Shouldn't the code be like this? You call the countdown and then the method.
public void someMethod() throws InterruptedException {
latch.countDown();
retrieveValue();
}
public class Solution {
CountDownLatch latch = new CountDownLatch(1);
public void someMethod() throws InterruptedException {
latch.await();
retrieveValue();
latch.countDown();
}
void retrieveValue() {
System.out.println("Value retrieved.");
}
public static void main(String[] args) throws InterruptedException {
Solution s1 = new Solution();
s1.someMethod();
}
}