Java Streams base the amount of parallelism on your hardware. But what if i want to always have the maximum amount of parallelism?
Consider the code below. I want each of the 10 tasks to concurrently run for 100 milliseconds.
long runUntil = System.currentTimeMillis() + 100;
IntStream.range(0, 10).parallel().forEach(i ->
{
int cnt = 0;
while(System.currentTimeMillis() < runUntil)
cnt++;
System.out.println(i + ": " + cnt);
});
However, the result I get is:
2: 56443
1: 67506
4: 74693
6: 70549
0: 0
3: 0
5: 0
7: 0
8: 0
9: 0
So only 4 tasks are executed in parallel, and the fifth task only starts when one of the first 4 is finished. I want all the tasks to start at approximately the same time, and not wait for eachother.
I don't agree that it's a duplicate of Custom thread pool in Java 8 parallel stream, because that question is about slow running tasks blocking other tasks, while in my case, I just want to know how I can (if I can) maximize the parallelism when using the Stream API.