gpt4 book ai didi

java.lang.ArrayIndexOutOfBoundsException : when using parallel stream to add elements to List

转载 作者:行者123 更新时间:2023-12-02 08:02:05 29 4
gpt4 key购买 nike

我正在努力优化 csv 文件的某些处理,因此试图加速某些 Jackson 的实现。所以我有:

List<T> testResults=new ArrayList();
Stream<T> testStream= Streams.stream(TestIterator);
testStream.parallel().forEach(p->testResults.add(p));

我在这里得到:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 360145
at java.util.ArrayList.add(Unknown Source)
at xml_test.opencsv.App.lambda$1(App.java:85)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.ForEachOps$ForEachTask.compute(Unknown Source)
at java.util.concurrent.CountedCompleter.exec(Unknown Source)
at java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
at java.util.concurrent.ForkJoinTask.doInvoke(Unknown Source)
at java.util.concurrent.ForkJoinTask.invoke(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp.evaluateParallel(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateParallel(Unkno

有什么想法吗?如果我删除“并行”,它可以工作,但速度非常慢。

最佳答案

ArrayList不是线程安全的实现。一种解决方案是将其包装为 Collections.synchronizedList() :

Returns a synchronized (thread-safe) list backed by the specified list.

List<T> testResults = Collections.synchronizedList(new ArrayList<>());

关于java.lang.ArrayIndexOutOfBoundsException : when using parallel stream to add elements to List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480851/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com