I was learning java stream api and I found this issue in code.
Here is my code
long s = System.currentTimeMillis();
IntStream.range(1, 10).parallel().forEach( x ->{
System.out.println( "Thread -> "+ Thread.currentThread().getName() +" "+ x );
});
long e = System.currentTimeMillis();
System.out.println("Time taken "+ (e-s) + " ms");
System.out.println("---------------------");
s = System.currentTimeMillis();
IntStream.range(1, 10).forEach( x ->{
System.out.println( "Thread -> "+ Thread.currentThread().getName() +" "+ x );
});
e = System.currentTimeMillis();
System.out.println("Time taken "+ (e-s) + " ms");
Here is the output
Thread -> main 6
Thread -> ForkJoinPool.commonPool-worker-7 2
Thread -> ForkJoinPool.commonPool-worker-7 5
Thread -> ForkJoinPool.commonPool-worker-13 1
Thread -> ForkJoinPool.commonPool-worker-11 4
Thread -> ForkJoinPool.commonPool-worker-3 3
Thread -> ForkJoinPool.commonPool-worker-15 9
Thread -> ForkJoinPool.commonPool-worker-9 7
Thread -> ForkJoinPool.commonPool-worker-5 8
Time taken using parallel stream 29 ms
-------------------------------------
Thread -> main 1
Thread -> main 2
Thread -> main 3
Thread -> main 4
Thread -> main 5
Thread -> main 6
Thread -> main 7
Thread -> main 8
Thread -> main 9
Time taken simple stream 1 ms
I have tried this code on sts and inteliJ IDE, results are same. Parallel is taking longer time than sequential. Is there a problem with my jdk? please suggest.