I have the following code (just an example that i wrote for this question) which simply calculates sum of a range I implemented it in three ways:
- Serial
- Parallel Stream
- With ForkJoinPool
Surprisingly the Serial method was the fastest one. In fact it takes %10 of the time of the other two.
What is the right configurations for Java Stream in order to make it faster? What wrong i am doing ?
package ned.main;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;
public class TestParallelStream {
static private void testParallelStream() {
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1000000");
ForkJoinPool forkJoinPool = new ForkJoinPool(10000);
Date start = new Date();
long sum1 = 0;
for (int i = 0; i < 1_000_000; ++i) {
sum1 += i * 10;
}
Date start1 = new Date();
long sum2 = IntStream.range(1, 1_000_000)
.parallel()
.map(x -> x * 10)
.sum();
Date start2 = new Date();
try {
long sum3 = forkJoinPool.submit(() ->
IntStream
.range(1, 1_000_000)
.parallel()
.map(x -> x * 10)
.sum())
.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
long serial = start1.getTime() - start.getTime();
long parallelstream = start2.getTime() - start1.getTime();
long withfork = start2.getTime() - start1.getTime();
System.out.println(serial + "," + parallelstream + "," + withfork);
}
public static void main(String[] args) {
testParallelStream();
}
}
Thanks