title: How does CountDownLatch works in Java?
body: <p>I am studying Synchronization in Java. I am not able to understand the exact mechanism of CountDownLatch. </p>
  
  <p>Does CountDownLatch <em>'counts down the latch'</em> (waits for completion of number of threads) as per the number of threads which are given at declaration? </p>
  
  <p>Here is the code I tried to understand:</p>
  
  <pre><code>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 &lt; 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();
      }
  }
  </code></pre>
  
  <p>In the example above:</p>
  
  <p>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: </p>
  
  <pre><code>CountDownLatch latch = new CountDownLatch(5);
  </code></pre>
  
  <p>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.:</p>
  
  <pre><code>Starting: 1
  Starting: 0
  Starting: 2
  Starting: 3
  Starting: 5
  Starting: 4
  Starting: 6
  all process completed
  </code></pre>
  
  <p>Here is output at alternate times:</p>
  
  <pre><code>Starting: 0
  Starting: 2
  Starting: 1
  Starting: 4
  Starting: 5
  Starting: 3
  all process completed
  
  Starting: 6
  </code></pre>
  
  <p>EDIT : The CountDownLatch should ideally countDown until 5 tasks are passed the latch. Here it is showing as either 6 or 7.</p>
  
  <p>What would be the fix for the code, if I want it to always display only 5 tasks before <strong>'all process completed'</strong> ?</p>