I am studying Synchronization in Java. I am not able to understand the exact mechanism of CountDownLatch.
Does CountDownLatch 'counts down the latch' (waits for completion of number of threads) as per the number of threads which are given at declaration?
Here is the code I tried to understand:
public class LatchExample implements Runnable {
private CountDownLatch latch;
private int id;
public LatchExample(int id, CountDownLatch latch){
this.id=id;
this.latch = latch;
}
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(5);
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 7; i++) {
executor.submit(new LatchExample(i,latch));
}
try {
latch.await();
System.out.println("all process completed");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
}
@Override
public void run() {
System.out.println("Starting: "+id);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
In the example above:
7 threads are spawned by ExecutorService (from the Thread pool). My understanding is that the latch should wait for completion of 6 threads (from 0 to 5), as defined by:
CountDownLatch latch = new CountDownLatch(5);
But the output that I get is not constant every time. Sometimes it waits for 6 threads to complete and sometimes it waits for 7 e.g.:
Starting: 1
Starting: 0
Starting: 2
Starting: 3
Starting: 5
Starting: 4
Starting: 6
all process completed
Here is output at alternate times:
Starting: 0
Starting: 2
Starting: 1
Starting: 4
Starting: 5
Starting: 3
all process completed
Starting: 6
EDIT : The CountDownLatch should ideally countDown until 5 tasks are passed the latch. Here it is showing as either 6 or 7.
What would be the fix for the code, if I want it to always display only 5 tasks before 'all process completed' ?