stream and parallelStream

前端 未结 3 2050
走了就别回头了
走了就别回头了 2021-01-05 12:31

I have a test code like this :

List list = new ArrayList<>(1000000);

for(int i=0;i<1000000;i++){
    list.add(i);
}

List

        
3条回答
  •  清歌不尽
    2021-01-05 12:54

    Using a Consumer, you have to worry about thread safety. A simpler solution it to let the Stream API accumulate the results.

    List values = IntStream.range(0, 1_000_000).parallel()
                                   .mapToObj(i -> new Date().toString())
                                   .collect(Collectors.toList());
    

    A key reason to avoid using a thread safe collector like Vector is it requires each thread to obtain a shared lock with is a bottleneck, i.e. you will spend time obtaining and releasing the lock and only one thread at a time can access it. You can easily end up with a solution which is slower than using one thread alone.

提交回复
热议问题