【发布时间】:2017-06-20 04:03:16
【问题描述】:
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 代替它。然后它运行正常,所有值都有值,但我不知道为什么?
【问题讨论】:
-
HashMapjavadoc (docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) 对此非常清楚,“请注意,此实现不同步。如果多个线程同时访问哈希映射,并且至少一个线程修改了在结构上,它必须在外部同步。”
标签: java thread-safety java-stream