stream and parallelStream

前端 未结 3 2037
走了就别回头了
走了就别回头了 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条回答
  •  萌比男神i
    2021-01-05 12:52

    values.add(String) is not thread safe. When you invoke this method from different threads without synchronization it is no guarantee that it will work as expected.

    To fix that you can:

    • use thread-safe collection like Vector or CopyOnWriteArrayLis.
    • Explicitly synchronize your code. For example put synchronize(this){values.add(new Date().toString())} into your code. Note i-> is outside synchronize block
    • Or in this case map elments to get new stream like in @PeterLawrey answer: IntStream.range(0, 1_000_000).parallel().mapToObj(i -> new Date().toString()).collect(Collectors.toList());

提交回复
热议问题