Nested for loops inside a parallel for loops gives incorrect results

70 Views Asked by At

I am iterating the foreach loop using parallelStream but inside i have a list of nested for loops.

During iteration its giving incorrect result each time with different value.

I really needs this parallel for loop execution to increase performance.

Expectation - 6k records

Result set after parallel iteration - 2k which also varies if I execute the same logic again. What is the difference when we execute a parallelstream with foreach() loop and foreachOrdered()loop? Which one offers a best result with good performance?

 //created a class
 public class Person{
     private Integer personId;
     private String personName;
 }

 //Arraylist that holds all the person details
 public Class PersonDetails{
     public void personData(){
         List<Person> personList = getPersonDetails();
         personList.parallelStream().forEach(person-> {
             // code logic to fetch data from different array list 
             // based on personid and create a set of combinations 
             // using nested for-loop.
        });
    }
}
        
        
1

There are 1 best solutions below

3
On

I have the question which is similar to @cyberbrain 's comment.

Does the nested for-loop read and write the same collection(List/Set)?

If so, please make your collection can be concurrent object type. e.g. CopyOnWriteArrayList or CopyOnWriteArraySet something like these.