title: Latch for different task types
body: <p>I am looking for a java concurrency solution to the following problem.</p>
  
  <p>There are some tasks being run, and a section of code C.</p>
  
  <ul>
  <li><p>C must wait for all tasks to complete. (With a timeout)</p></li>
  <li><p>No tasks may commence until C has finished.</p></li>
  </ul>
  
  <p>I have looked through the java.concurrency package and I found a few things of interest, but nothing seems to work quite right:</p>
  
  <ul>
  <li>Phasers would allow one way blocking, but not two way.</li>
  <li>Semaphores, ForkJoinTasks and others have counter-type features but none seem to do what I want.</li>
  </ul>
  
  <p>I believe I could construct something using a phaser and a lock like so:</p>
  
  <pre><code>void C() {
      synchronized(lock) {
          phaser.awaitAdvanceInterruptibly(phase, 1, TimeUnit.SECONDS);
          // Start work anyway if a task is taking too long.
          doWork();
      }
  }
  
  void someTask() {
      synchronized(lock) {
          phaser.register();
      }
      doTask().thenRun(
          () -&gt; phaser.arriveAndDeregister()
      );
  }
  </code></pre>
  
  <p>Now while I'm fairly sure this would work, I'm also aware its a bad idea to try to build your own concurrency solution. Is there a better way of doing this?</p>
  
  <p>If there isn't, what would I use for the <code>phase</code> argument?</p>
  
  <p><strong>Edit</strong>: This problem is within a project involving a web client connection, and therefore the tasks arrive unpredictably. However, it is possible that this situation could be avoided by more careful design.</p>