Reputation: 337
I am working to optimize some processing of an csv file , therefore trying to accelerate some Jackson implementation. So I have:
List<T> testResults=new ArrayList();
Stream<T> testStream= Streams.stream(TestIterator);
testStream.parallel().forEach(p->testResults.add(p));
and here i get :
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
Any ideas whats going on? If I remove the 'parallel' it works , but is extremely slow.
Upvotes: 2
Views: 1263
Reputation: 117587
ArrayList
is not a thread-safe implementation. One solution is to wrap it with Collections.synchronizedList()
:
Returns a synchronized (thread-safe) list backed by the specified list.
List<T> testResults = Collections.synchronizedList(new ArrayList<>());
Upvotes: 4