我正在研究 Java 流,想知道这段代码是否有问题。由于我使用的是并行流,所以我使用了 ConcurrentHashMap。
class Person {
private String name;
public String getName() {
return this.name;
}
}
和
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());
最佳答案
如果 map 正在积极更新,您可能会在 containsKey
和 get
之间进行竞争。相反,你可能会写类似的东西
list.parallelStream()
.filter(id -> {
Person person = map.get(id);
return person != null && !Strings.isNullOrEmpty(person.getName());
})
.collect(Collectors.toList());
使用 parallelStream
与此无关——没关系。它在同一键上对 ConcurrentMap
进行两次单独调用,并期望它们具有一致的结果,这就是问题所在。
关于java - 并行流概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512680/