Concept of parallel threads

I am studying Java threads and want to know if there is something wrong with this code. Since I use parallel thread, I 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());
+4
source share
2 answers

If the map is actively updating, you may have a race between containsKeyand get. Instead, you can write something like

list.parallelStream()
    .filter(id -> {
       Person person = map.get(id);
       return person != null && !Strings.isNullOrEmpty(person.getName());
     })
    .collect(Collectors.toList());

Using parallelStreamhas nothing to do with it - it's great. He makes two separate calls in ConcurrentMapon the same key and expects them to have consistent results, which is the problem.

+5
source

, . .

HashMap, . , .

+2

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


All Articles