0

I have a list in which items are iterated and processed. These should be added to another list after being processed. This is legacy code and I have to implement parallel processing.

class demo{

    public void function1(){

        List<TestPojo> newList = new ArrayList<>();

        oldList.parallelStream.forEach(item->
        function2(newList,item)
        ); 

    }

    public void function2(List<TestPojo> newList, Item item){

        TestPojo testPojo = formPojo(item);

        synchronized(newList){
            newList.add(testPojo);
        }

    }



}

Owing to certain legacy conditions, I cannot change the function signatures. Will this cause an issue? Am I breaking any rules by not using a synchronized list?

justlikethat
  • 329
  • 2
  • 12
  • The code seems alright to me. Not sure what the question is tho. – Amongalen Jul 16 '20 at 13:25
  • @Amongalen, I wanted to know if I'm breaking any rules by not using a synchronized list. – justlikethat Jul 16 '20 at 13:27
  • 3
    are you worried about race conditions or concurrent operations? why not try https://stackoverflow.com/questions/6916385/is-there-a-concurrent-list-in-javas-jdk ? Unless you disclose *why* you had to use `synchronized`, your actual code could have been reduced to `List newList = oldList.parallelStream() .map(item -> formPojo(item)) .collect(Collectors.toList());` – Naman Jul 16 '20 at 13:29
  • @Naman, thanks for the reply. I understand the solutions provided in the link. I was wondering if doing a manual synchronization on a list that has not been declared as a synchronized list still help given that function2 is called within parallel streams. – justlikethat Jul 16 '20 at 13:32
  • 1
    the synchronized will prevent real trouble, but all parallel-processing will serialize at this point, only "TestPojo testPojo = formPojo(item);" will be processed parallel as result. to avoid this you could use a approach like "foreach().collect(Collector ...". Initializing the ArrayList with a expected size should improve performance (avoid resizing the internal structures while add) – Michael Hauptmann Jul 16 '20 at 13:33

0 Answers0