title: CountDownLatch vs. Semaphore
body: <p>Is there any advantage of using</p>
  
  <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html" rel="noreferrer"><strong>java.util.concurrent.CountdownLatch</strong></a> </p>
  
  <p>instead of</p>
  
  <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html" rel="noreferrer"><strong>java.util.concurrent.Semaphore</strong></a>? </p>
  
  <p>As far as I can tell the following fragments are almost equivalent:</p>
  
  <p><strong>1. Semaphore</strong></p>
  
  <pre><code>final Semaphore sem = new Semaphore(0);
  for (int i = 0; i &lt; num_threads; ++ i)
  {
    Thread t = new Thread() {
      public void run()
      {
        try
        {
          doStuff();
        }
        finally
        {
          sem.release();
        }
      }
    };
    t.start();
  }
  
  sem.acquire(num_threads);
  </code></pre>
  
  <p><strong>2: CountDownLatch</strong></p>
  
  <pre><code>final CountDownLatch latch = new CountDownLatch(num_threads);
  for (int i = 0; i &lt; num_threads; ++ i)
  {
    Thread t = new Thread() {
      public void run()
      {
        try
        {
          doStuff();
        }
        finally
        {
          latch.countDown();
        }
      }
    };
    t.start();
  }
  
  latch.await();
  </code></pre>
  
  <p>Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)</p>
  
  <p>So in what situation might the latch be preferable?</p>