title: CountdownLatch combine await(maxTime) and countdown()
body: <p>I have several threads running for an almost infinite time and number of iteration. The iteration count being reset to 0 when a best solution has been found. A max number of iteration is set to prevent an infinite loop.</p>
  
  <p>I use a countdownlatch to stop the process when all thread have reach the max number of iteration. In other word, when a thread reach the max number of iteration, it notifies my main thread using <em>notifyThreadStop()</em> which, when all thread are stopped, triggers countdown().</p>
  
  <p>Note: my threads are running inside a FixedThreadPool ExecutorService.</p>
  
  <p>I would like to add a maxTime latch. So what i did is the following  </p>
  
  <pre><code>List&lt;Runnable&gt; r = .... //(contains all my runnables)
  myExecutorService.invokeAll(r);
  
  if(maxtime &gt; 0){
      mylatch.await(maxTime,TimeUnit.Seconds);
      (1)
      do stuff...
      exit;
  }
  else{
      mylatch.await();
      myExecutorService.shutdownNow();
      do stuff...
      exit;
  }
  </code></pre>
  
  <p>Now, I know that if the countdown has triggered the latch, it means that all threads are stopped so I can shutdownNow my ExecutorService.</p>
  
  <p>It is not the case when the max time has been reached. So in (1) i would like to iterate through all my runners to terminate them in a civilized way :-) . For that, i have defined a function requestTermination() that, simply put, set the iterationCounter to MaxIterationCount in my runnables. </p>
  
  <p>So (1) would become</p>
  
  <pre><code>    for(Runnable runner: r){
          if(r.getIsRunning()){r.requestTermination();}
      }
      (2)
  </code></pre>
  
  <p>Now, I need to wait again until all threads are really stopped before i can proceed.... hmmmm just thinking that i could have an additional latch and work with that.</p>
  
  <p>So (2) would become</p>
  
  <pre><code>    mylatch2.await();
      myExecutorService.shutdownNow();
  </code></pre>
  
  <p>Of course, my function <em>notifyThreadStop()</em> would need to be modified of it and would need a flag telling it to do a countdown() on mylatch2 as opposed to mylatch.</p>
  
  <p>I think I have just answered my question but since all this has been written, I'll leave it here for others to refer to it. </p>
  
  <p><strong>The question would now be</strong>: Any better way of handling this? Would a shutdownNow() in (1) or (2) be the only thing required? <strong>Knowing</strong> that my my threads have to close their own log file and shutdown their inner Callable thread*ss* before exiting.</p>