title: Java: Set timeout for threads in a ThreadPool
body: <p>I want to set timeouts for threads which are executed within a thread pool. At the moment I have following code:</p>
  
  <pre><code>ExecutorService executor = Executors.newFixedThreadPool(8);
  for(List&lt;String&gt; l: partition) {            
      Runnable worker = new WorkerThread(l);
      executor.execute(worker);
  }       
  
  executor.shutdown();
  while (!executor.isTerminated()) {
  
  }
  </code></pre>
  
  <p>The code just splits a big list of objects into sublists and process these sublist within single threads. But this is not the point. </p>
  
  <p>I want to give each single thread in the thread pool a timeout. For only one thread in the pool I found following solution:</p>
  
  <pre><code>Future&lt;?&gt; future = null;
  
  for (List&lt;String&gt; l : partition) {
      Runnable worker = new WorkerThread(l);
      future = executor.submit(worker);
  }
  
  try {
      System.out.println("Started..");
      System.out.println(future.get(3, TimeUnit.SECONDS));
      System.out.println("Finished!");
  } catch (TimeoutException e) {
      System.out.println("Terminated!");
  }
  </code></pre>
  
  <p>But this would not work for more than one thread. Maybe I have to put each thread in a <code>List&lt;Future&gt;</code> list and iterate over this list and set a timeout for each <code>future</code> object?</p>
  
  <p>Any suggestions?</p>
  
  <p>EDIT AFTER USING CountDownLatch:</p>
  
  <pre><code>CountDownLatch doneSignal = new CountDownLatch(partition.size());
  List&lt;Future&lt;?&gt;&gt; tasks = new ArrayList&lt;Future&lt;?&gt;&gt;();
  ExecutorService executor = Executors.newFixedThreadPool(8);
  for (List&lt;String&gt; l : partition) {
      Runnable worker = new WorkerThread(l);
      tasks.add(executor.submit(doneSignal, worker));
  }
  
  doneSignal.await(1, TimeUnit.SECONDS);
  if (doneSignal.getCount() &gt; 0) {
      for (Future&lt;?&gt; fut : tasks) {
      if (!fut.isDone()) {
          System.out.println("Task " + fut + " has not finshed!");
          //fut.cancel(true) Maybe we can interrupt a thread this way?!
      }
      }
  }
  </code></pre>
  
  <p>Works good so far. </p>
  
  <p>So next question is how to interrupt a thread which is timed out? I try <code>fut.cancel(true)</code> and add following construct in some critical loops in the worker thread:</p>
  
  <pre><code>if(Thread.interrupted()) {
      System.out.println("!!Thread -&gt; " + Thread.currentThread().getName() + " INTERRUPTED!!");
          return;
  }
  </code></pre>
  
  <p>So the worker thread is "killed" after the timeout. Is this a good solution?</p>
  
  <p>Furthermore: Is it possible to get the name of the thread which timed out over the <code>Future</code> interface? At the moment I have to print out the name in the if condition of the <code>Thread.interrupted()</code> construct.</p>
  
  <p>Thanks for help!</p>
  
  <p>Regards</p>