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?
source share