java使用parallelStream foreach创建HashMap,但有时值为空
Java代码如下:
List<Detail> DbDetails = ... Like 50000 rows records
Map<Long, List<Detail>> details = new HashMap();
DbDetails .parallelStream().forEach(detail -> {
Long id = detail.getId();
details.computeIfAbsent(id, v -> new ArrayList<>()).add(detail);
});
Then ...
details.entrySet().stream().forEach(e -> {
e.getValue(); // Some value is empty
});
我猜这是因为HashMap是线程不安全的,所以我用Hashtable代替它。然后它运行正常,所有的值都有值,但我不知道为什么
# 1 楼答案
HashMap
不是线程安全的,所以不要使用并行流再说,既然溪流能为你做这件事,为什么还要在那里做呢