0

I'm implementing a simple sum programm, to sum up an array of integers using recursive multi-thread method.(ExecutorService & Callable).

But I got tons of Exceptions

public class ExecutorServiceSum implements Callable<Integer> {
 int[] a;
 int lo;
 int hi;
 static ExecutorService ex;

 ExecutorServiceSum(ExecutorService ex, int[] a, int lo, int hi) {
  this.a = a;
  this.lo = lo;
  this.hi = hi;
 }
 @Override
 public Integer call() throws Exception {
  int size = hi - lo;
  if (size == 1) {
   return a[hi];
  }
  //exit of the recursion 

  int mid = size / 2;
  ExecutorServiceSum e1 = new ExecutorServiceSum(ex, a, lo, lo + mid);
  ExecutorServiceSum e2 = new ExecutorServiceSum(ex, a, lo + mid, hi);
  //branching to subproblems

  Future<Integer> f1 = ex.submit(e1);
  Future<Integer> f2 = ex.submit(e2);

  return f1.get() + f2.get();
 }

 public static void main(String[] args) throws InterruptedException,
 ExecutionException {
  int[] a = new int[200000];
  for (int i = 0; i < a.length; i++) {
   a[i] = 1;
  }
  //this is the array the programm needs to sum up 

  ExecutorService exs = Executors.newFixedThreadPool(20);
  //creating a ThreadPool using newFixedThreadPool

  ExecutorServiceSum ess = new ExecutorServiceSum(ex, a, 0, a.length);
  //creating a Callable task obejct 

  Future < Integer > f3 = exs.submit(ess);
  //submitting the Callable task object to the ThreadPool
  //store the result in Future object

  System.out.println(f3.get());
 }
}

the following are exceptions:

Exception in thread "main" java.util.concurrent.ExecutionException: 
java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at ExecutorServiceSum.main(ExecutorServiceSum.java:54)
Caused by: java.lang.NullPointerException
    at ExecutorServiceSum.call(ExecutorServiceSum.java:31)
    at ExecutorServiceSum.call(ExecutorServiceSum.java:1)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Questions:

  1. why the get() method get Unknown Source?

  2. Future object contains unfinished return result?

  3. how to fix this code?

Flown
  • 11,480
  • 3
  • 45
  • 62

0 Answers0