I wrote the following code to learn parallelStream.
public class Main {
    public static void main(String[] args) {
        List<Integer> set = IntStream.iterate(2000000, x -> x - 1)
                .boxed()
                .limit(2000000)
                .collect(Collectors.toList());
        for (int x = 0; x < 5; x++) {
            //================= parallelStream ===============
            LocalTime start = LocalTime.now();
            set.parallelStream().sorted().findFirst().get();
            Duration duration = Duration.between(start, LocalTime.now());
            System.out.println("parallelStream: " + duration.toMillis());
        }
    }
}
Every time I ran this program, I found that the first parallel stream was always much slower than the subsequent parallel streams.
Here are some test data:
parallelStream: 113
parallelStream: 24
parallelStream: 41
parallelStream: 14
parallelStream: 14
Process finished with exit code 0
-
parallelStream: 154
parallelStream: 25
parallelStream: 47
parallelStream: 13
parallelStream: 15
Process finished with exit code 0
See, the first parallel stream operation always takes several times as long as the subsequent parallel stream costs.
Why is that? I would appreciate it if someone could help me.
