title: Set a timeout on individual threads when using CompletableFuture using a ThreadPoolExecutor
body: <p>I have a program which executes things asynchronously using a ThreadPoolExecutor. I use CompletableFutures in Java 8 to schedule these tasks and then have them executed by the threads available in the thread pool. </p>
  
  <p>My code looks like this:</p>
  
  <pre><code>public class ThreadTest {
  
      public void print(String m) {
          System.out.println(m);
      }
  
      public class One implements Callable&lt;Integer&gt; {
  
          public Integer call() throws Exception {
              print("One...");
              Thread.sleep(6000);
              print("One!!");
              return 100;
          }
      }
  
      public class Two implements Callable&lt;String&gt; {
  
          public String call() throws Exception {
              print("Two...");
              Thread.sleep(1000);
              print("Two!!");
              return "Done";
          }
      }
  
      @Test
      public void poolRun() throws InterruptedException, ExecutionException {
          int n = 3;
          // Build a fixed number of thread pool
          ExecutorService pool = Executors.newFixedThreadPool(n);
  
          CompletableFuture futureOne = CompletableFuture.runAsync(() -&gt; new One());
          // Wait until One finishes it's task.
          CompletableFuture futureTwo = CompletableFuture.runAsync(() -&gt; new One());
          // Wait until Two finishes it's task.
          CompletableFuture futureTwo = CompletableFuture.runAsync(() -&gt; new Two());
  
          CompletableFuture.allOf(new CompletableFuture[]{futureOne, futureTwo, futureThree}).get();
          pool.shutdown();
      }
  }
  </code></pre>
  
  <p>I need to set a timeout on each individual thread, for example to timeout at 10 minutes. 
  I looked into the .get(TimeUnit timeUnit) method for CompletableFuture, but I wasn't sure if that sets a timeout on the thread pool or on the individual thread itself. </p>
  
  <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#get-long-java.util.concurrent.TimeUnit-" rel="nofollow noreferrer">https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#get-long-java.util.concurrent.TimeUnit-</a></p>
  
  <p>Or should I be changing the way I use the executor service to set timeouts on individual threads? </p>
  
  <p>Thanks! </p>