Parallel thread gives null elements how to do in Java 8

I get some strange results when trying to use a parallel thread, and I know a workaround, but it doesn't seem ideal

// Create the set "selected" somethingDao.getSomethingList().parallelStream() .filter(something -> !selected.contains(something.getSomethingId())) .forEach(something -> somethingSubGroupDTO.addFilterDTO( new FilterDTO(something.getSomethingName(), something.getSomethingDescription(), false)) ); selected.clear(); 

somethingDao.getSomethingList returns a List

selected is a HashSet<Integer> that does not change during this operation.

somethingSubGroupDTO.addFilterDTO is a helper function that adds to an unsynchronized list. This is problem. As an unsynchronized list, I get fewer items in the list than expected, and some items are null. If I include it in the synchronized list, it will work. Obviously, adding a lock to a parallel thread is not ideal.

At a high level, I know that this can be done so that each thread performs its own processing, and when they join, they will be aggregated. (At least I can imagine such a process without competition). However, since I'm new to Java 8 thread processing, I don't know how to do this. How can I do the same operation without competition at one point?

+5
source share
1 answer

Do not use forEach and instead create your stream in List :

 somethingDao.getSomethingList().parallelStream() .filter(something -> !selected.contains(something.getSomethingId())) .map(something -> new FilterDTO(something.getSomethingName(), something.getSomethingDescription(), false)) .collect(toList()); 

You can then set the returned list directly to your somethingSubGroupDTO object instead of adding one item at a time.

+8
source

Source: https://habr.com/ru/post/1234797/


All Articles