I am exploring Java streams and wanted to know if there is anything wrong with this code. Since I am using parallel stream, I have used ConcurrentHashMap.
class Person {
private String name;
public String getName() {
return this.name;
}
}
and
ConcurrentHashMap<Integer, Person> map = <Mapping of id to Person>
List<Integer> list = <list of Id>
list = list.parallelStream()
.filter(id -> map.containsKey(id)
&& !Strings.isNullOrEmpty(map.get(id).getName()))
.collect(Collectors.toList());
If the map is being actively updated, you may have a race between containsKey and get. Instead, you might write something like
list.parallelStream()
.filter(id -> {
Person person = map.get(id);
return person != null && !Strings.isNullOrEmpty(person.getName());
})
.collect(Collectors.toList());
Using parallelStream has nothing to do with this -- that's fine. It's doing two separate calls to the ConcurrentMap on the same key and expecting them to have consistent results that's the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With