I have developed a sample java program to understand countdownlatch & initialized the countdownlatch with count 4. I expected that after countDown method, the getCount() would return the remaining count for the countdownlatch. But, in the following example:-
public static void main(String args[]) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
Worker first = new Worker(latch, "WORKER-1");
Worker second = new Worker(latch, "WORKER-2");
Worker third = new Worker(latch, "WORKER-3");
Worker fourth = new Worker(latch, "WORKER-4");
first.start();
second.start();
third.start();
fourth.start();
latch.await();
System.out.println("Final Count:- " + latch.getCount());
}
}
class Worker extends Thread {
private CountDownLatch latch;
public Worker(CountDownLatch latch, String name) {
super(name);
this.latch = latch;
}
@Override
public void run() {
latch.countDown();
System.out.println("Count:- " + latch.getCount());
System.out.println(Thread.currentThread().getName() + " finished");
}
}
The output is :-
Count:- 2
Count:- 1
Count:- 2
WORKER-3 finished
WORKER-1 finished
WORKER-2 finished
Count:- 0
Final Count:- 0
WORKER-4 finished.
The count is returned as 2 for two times in the output. Is there anything wrong in my code?
It is not a problem. How is CountDownLatch used in Java Multithreading?
This method only do a volatile
read, not a synchronised
read.
/**
* Returns the current count.
*
* <p>This method is typically used for debugging and testing purposes.
*
* @return the current count
*/
public long getCount() {
return sync.getCount();
}