title: Using Future with ExecutorService
body: <p>I need to execute two tasks in parallel and wait for them to complete. Also I need the result from the second task, for that I am using <code>Future</code>. </p>
  
  <p>My question is that DO I need <code>executor.awaitTermination</code> to join the tasks or <code>Future.get()</code> will take care of it. Also is there a better way to achieve this with Java 8?</p>
  
  <pre><code>public class Test {
  
      public static void main(String[] args) {
          test();
          System.out.println("Exiting Main");
      }
  
      public static void test() {
          System.out.println("In Test");
          ExecutorService executor = Executors.newFixedThreadPool(2);
  
          executor.submit(() -&gt; {
              for(int i = 0 ; i&lt; 5 ; i++) {
                  System.out.print("["+i+"]");
                  try {
                      Thread.sleep(1000);
                  } catch (Exception e) {e.printStackTrace();}
              }
          });
  
          Future&lt;String&gt; result = executor.submit(() -&gt; {
              StringBuilder builder = new StringBuilder();
              for(int i = 0 ; i&lt; 10 ; i++) {
                  System.out.print("("+i+")");
                  try {
                      Thread.sleep(1000);
                  } catch (Exception e) {e.printStackTrace();}
                  builder.append(i);
              }
              return builder.toString();
          });
  
          System.out.println("shutdown");
          executor.shutdown();
          // DO I need this code : START
          System.out.println("awaitTermination");
          try {
              executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
          } catch (InterruptedException e) {
              System.out.println("Error");
          }
          // DO I need this code : END
          System.out.println("Getting result");
          try {
              System.out.println(result.get());
          } 
          catch (InterruptedException e) {e.printStackTrace();} 
          catch (ExecutionException e) {e.printStackTrace();}
          System.out.println("Exiting Test");
      }
  
  }
  </code></pre>
  
  <p>OUTPUT with <strong>awaitTermination</strong>:</p>
  
  <pre><code>In Test
  [0]shutdown
  (0)awaitTermination
  [1](1)[2](2)[3](3)[4](4)(5)(6)(7)(8)(9)Getting result
  0123456789
  Exiting Test
  Exiting Main
  </code></pre>
  
  <p>OUTPUT without <strong>awaitTermination</strong>:</p>
  
  <pre><code>In Test
  [0]shutdown
  Getting result
  (0)[1](1)[2](2)[3](3)[4](4)(5)(6)(7)(8)(9)0123456789
  Exiting Test
  Exiting Main
  </code></pre>