title: Java - splitting work to multiple threads
body: <p>I am posed with the following problem: I need to split work across multiple threads for perfomance reasons, but I am not sure what approach to take.</p>
  
  <p>Firstly, the task I would be supplying should return a value and take a parameter. Additionally, the main method (doing the main bit of work, not <code>static main()</code> ) is already running on separate thread and is invoked periodically. Also, this method must at some point WAIT for all threads to finish and then proceed.</p>
  
  <p>One approach (most obvious to me) is to schedule each job on a separate thread and store results in class vars:</p>
  
  <pre><code>public Object result1, result2;
  
  public void mainMethod() throws InterruptedException {
      final Thread thread = new Thread(new Runnable() {
          @Override
          public void run() {
              result1 = expensiveMethod("param1");
          }
      });
  
      final Thread thread1 = new Thread(new Runnable() {
          @Override
          public void run() {
              result2 = expensiveMethod("param2");
          }
      });
  
      thread1.join();
      thread.join();
  
      //Do rest of work
  }
  
  private Object expensiveMethod(Object param){
      // Do work and return result
  }
  </code></pre>
  
  <p>This is a bit ugly and not ideal, since as I said, mainMethod is invoked many times, and I do not want any race conditions on setting the result variables. Ideally, I would like to make them local variables, but I cannot make them accessible from within the run method, unless they are final, and then I cannot assign values to them...</p>
  
  <p>Another approach I though about doing was this:</p>
  
  <pre><code>public void mainMethod() throws InterruptedException, ExecutionException {
      String obj1, obj2;
  
      final ExecutorService executorService = Executors.newFixedThreadPool(16);
      final Future&lt;String&gt; res1 = executorService.submit(new Callable&lt;String&gt;() {
          @Override
          public String call() throws Exception {
              return expensiveMethod("param1");
          }
      });
      final Future&lt;String&gt; res2 = executorService.submit(new Callable&lt;String&gt;() {
          @Override
          public String call() throws Exception {
              return expensiveMethod("param2");
          }
      });
  
      obj1 = res1.get();
      obj2 = res2.get();
  
  }
  
  private String expensiveMethod(String param) {
      // Do work and return result
  }
  </code></pre>
  
  <p>This automatically waits on these two computations from main method and allows me to store the results locally. What to you guys think? Any other approaches?</p>