-1

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?

xingbin
  • 27,410
  • 9
  • 53
  • 103

2 Answers2

0

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();
}
rockfarkas
  • 132
  • 2
  • 8
  • It has nothing to do with synchronised read. Even it is a synchronised read, it could also get `Count:- 2` twice. Like I said in my answer. https://stackoverflow.com/a/54608472/6690200 – xingbin Feb 09 '19 at 17:59
0

The four Workers are running at the same time. Since latch.countDown(); and latch.getCount() are not atomic, the execution order could be:

thread1 latch.countDown();
thread2 latch.countDown();
thread1 System.out.println("Count:- " + latch.getCount()); // Count:- 2
thread2 System.out.println("Count:- " + latch.getCount()); // Count:- 2
xingbin
  • 27,410
  • 9
  • 53
  • 103