user3704576
user3704576

Reputation: 169

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());

Upvotes: 4

Views: 229

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198103

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.

Upvotes: 5

Andreas
Andreas

Reputation: 159096

The map is concurrent, so it can handle multi-threaded access. No synchronizing or locking needed.

In your case, a regular HashMap would work too, because you are only querying the map. As long a nobody updates the list while streaming, you have no multi-threaded contention.

Upvotes: 2

Related Questions