I'm playing with parallel execution in Java, now. Yesterday I tried to measure execution time and got some unclear results.
Task : sum array using parallel mode and sequential. Here is my code for parallel:
public static int sumArrayParallel(int[] numbers) throws ExecutionException, InterruptedException {
int cpus = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(cpus);
List<FutureTask<Integer>> tasks = new ArrayList<>();
int blockSize = (numbers.length + cpus - 1) / cpus;
for (int i = 0; i < numbers.length; i++) {
final int start = blockSize * i;
final int end = Math.min(blockSize * ( i + 1 ), numbers.length);
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
public Integer call() {
int sub = 0;
for (int j = start; j < end; j++)
sub += numbers[j];
return sub;
}
});
tasks.add(futureTask);
service.execute(futureTask);
}
int sum = 0;
for(Future<Integer> task: tasks)
sum += task.get();
service.shutdown();
return sum;
}
And pretty simple for sequential:
public static int sumArraySequential(int[] arr) {
int sum = 0;
for( int num : arr ) {
sum += num;
}
return sum;
};
So, sequential function works 2-4 times faster than parallel.What I'm doing wrong?