I was testing the performance of java 8 parallel stream api by creating a simple loop and adding elements in an array.
I am getting a huge performance boost over non parallel one.
But when I am checking my task manager I am seeing an uncontrolled CPU usage, it eats up all my CPU during that period.

here is my sample code,
    public static void withIfElse(boolean sorted) {
    int[] arr = new int[32768];
    Random rand = new Random();
    for(int i = 0;i < arr.length;i++)
        arr[i] = rand.nextInt(256);
    if(sorted)
        Arrays.parallelSort(arr);
    long nst = System.currentTimeMillis();
    long sum = 0;
    for(int j=0;j<100000;j++) {
        sum += Arrays.stream(arr).parallel().filter(m->m>=128).reduce((m,n)-> m+n).getAsInt();
    }
    System.out.printf("Time taken for boolean %b is %d ms. \n",sorted,(System.currentTimeMillis()-nst));
}
I am able to achieve almost 2x to 8x performance boost.
But ,
Cpu usage is uncontrolled. Is there any way to force java to only 2 cores ?
I have also tried setting
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1");
But still CPU usage is high.
Also is it recommended to use parallel stream?, because suppose in my application I have 10 user threads, or a web application where each request is a thread, in that case if I start a parallel stream on multiple threads which eventually eat all my cpu, there will be so many context switching.
 
     
     
     
    

