I'm trying to sum a table with threads. I'm creating a table with given length and then trying to create a sum with given name of threads.
Every thread is taking a part of table, according to his indeks.
For example:
Table with 12 elements on 3 threads:
0 thread taking [0, 3, 6, 9] elements
1 thread taking [1, 4, 7, 10] elements
2 thread taking [2, 5, 8, 11] elements
Threads are summing that numbers and then returning result. After it, I'm summing it all together, and getting result.
This is my single Callable object implementation:
public class TableSumThread implements Callable<Integer> {
private int indeks;
private int[] table;
public TableSumThread(int indeks, int[] table) {
this.indeks = indeks;
this.table = table;
}
@Override
public Integer call() throws Exception {
int iter = indeks;
int sum = 0;
while(iter < table.length) {
sum += table[iter];
iter += indeks;
}
return sum;
}
}
This is my "Executor":
public class TableSumExecutor {
private int[] table;
private int executors;
public Integer execute() {
ExecutorService executorService = Executors.newFixedThreadPool(executors);
List<Future<Integer>> results = new ArrayList<Future<Integer>>(executors);
for (int i = 0; i < executors; i++) {
Callable<Integer> task = new TableSumThread(i, table);
results.add(executorService.submit(task));
}
System.out.println("After creating all threads.");
int suma = sum(results);
return suma;
}
private int sum(List<Future<Integer>> results) {
int sum = 0;
for (int i = 0; i < results.size(); i++) {
try {
sum += results.get(i).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
return sum;
}
Main:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Table length: ");
int nTable = scanner.nextInt();
System.out.println("Threads number: ");
int nThreads = scanner.nextInt();
Random random = new Random();
int[] tablica = new int[nTable];
for (int i = 0 ; i < tablica.length ; i++)
tablica[i] = Math.abs(random.nextInt() % 9 + 1);
TableSumExecutor tableSumExecutor = new TableSumExecutor(tablica, nThreads);
int result = tableSumExecutor.execute();
System.out.println("And the result is: " + result);
}
Everything is fine, threads performing all the tasks, but program is blocking on:
sum += results.get(i).get();
I'm not getting any exception, it's just blocking. I've checking it also on debugger. All task were finished, and result was waiting for final step.
I'm probably not using get() of Future type properly?
EDIT. Ok, I solved a problem. But program is not ending after all. When I'm checking after displaying result in main executorService.isShutdown() It's false. Should I terminate all threads manualy, or it should terminate automatically?