0

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.
        });
    }
}
        
        
  • 2
    Please don't just describe your code. Include a [example] with your question instead. – Federico klez Culloca Nov 30 '22 at 08:22
  • And please also include your inputs, expected results and actual results. – Federico klez Culloca Nov 30 '22 at 08:23
  • does the code inside the lambda expression access (read/modify) any data from outside i common (e.g. reads or writes to the same file, the same database, the same objects in memory) or do you really just create new stuff in your code or modify that person object? It would be quite unusual to work without any side effects inside a `.foreach`. Can you describe that "fetch data from different array list" and "create a set of combinations" a bit more in details? – cyberbrain Nov 30 '22 at 12:51

1 Answers1

0

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.

Wise Lin
  • 11
  • 2
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/33570972) – Bö macht Blau Jan 08 '23 at 09:35
  • I'm answering this question and I have provided solutions to solve it, maybe you should check the content first. – Wise Lin Jan 09 '23 at 09:18
  • Sorry I misunderstood your intention. I suppose some of it was lost in translation (looks like none of us has English as their first language) – Bö macht Blau Jan 09 '23 at 12:09