Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Streams concept

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());
like image 705
user3704576 Avatar asked Mar 14 '23 19:03

user3704576


1 Answers

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.

like image 85
Louis Wasserman Avatar answered Mar 28 '23 08:03

Louis Wasserman