title: Flexible CountDownLatch?
body: <p>I have encountered a problem twice now whereby a producer thread produces N work items, submits them to an <code>ExecutorService</code> and then needs to wait until all N items have been processed.</p>
  
  <p><strong>Caveats</strong></p>
  
  <ul>
  <li><strong>N is not known in advance</strong>.  If it were I would simply create a <code>CountDownLatch</code> and then have producer thread <code>await()</code> until all work was complete.</li>
  <li>Using a <code>CompletionService</code> is inappropriate because although my producer thread needs to block (i.e. by calling <code>take()</code>) there's <strong>no way of signalling that all work is complete</strong>, to cause the producer thread to stop waiting.</li>
  </ul>
  
  <p>My current favoured solution is to use an integer counter, and to <strong>increment</strong> this whenever an item of work is submitted and to <strong>decrement</strong> it when a work item is processed.  Following the subsmission of all N tasks my producer thread will need to wait on a lock, checking whether <code>counter == 0</code> whenever it is notified.  The consumer thread(s) will need to notify the producer if it has decremented the counter and the new value is 0.</p>
  
  <p>Is there a better approach to this problem or is there a suitable construct in <code>java.util.concurrent</code> I should be using rather than "rolling my own"?</p>
  
  <p>Thanks in advance.</p>