在并行流中的hashmap中插入值时的线程安全性

时间:2018-04-10 06:43:20

标签: java concurrency java-8 hashmap concurrenthashmap

我需要使用10秒的超时进行异步调用,并且需要对地图中的每个元素执行此操作。异步调用的结果存储在另一个映射中。在这种情况下使用HashMap是否安全,或者我是否需要使用ConcurrentMap

Map<String, String> x = ArrayListMultimap.create();
Map<String, Boolean> value = Maps.newHashMap();

x.keySet().paralleStream().forEach(req -> {
   try {
      Response response = getResponseForRequest(req);
      value.put(req, response.getTitle());
   } catch(TimeoutException e) {
      value.put(req, null);
   }
}

这个线程安全吗?我无法理解。我知道另一种方法是创建一个并发的hashmap,并考虑一些其他填充值而不是null,因为Concurrent map不支持null值。

1 个答案:

答案 0 :(得分:6)

您可以使用.map()代替.forEach()并返回使用Collectors.toMap()终止函数创建的地图,而不是并行修改外部地图。请考虑以下示例:

Map result = x.keySet()
  .parallelStream()
  .map(req -> {
    try {
      Response response = getResponseForRequest(req);
      return new AbstractMap.SimpleEntry<>(req, response.getTitle());
    } catch (TimeoutException e) {
      return new AbstractMap.SimpleEntry<>(req, null);
    }
  })
  .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));

在此示例中,您将返回一个SimpleEntry对象,该对象表示每个元素的键和值,并在处理完所有条目后将其收集到单个映射中。

简化

Holger建议删除AbstractMap.SimpleEntry更简化的解决方案:

Map result = x.keySet()
  .parallelStream()
  .collect(Collectors.toMap(Function.identity(), req -> {
    try {
      Response response = getResponseForRequest(req);
      return response.getTitle()
    } catch (TimeoutException e) {
      return null
    }
  }));

选择适合你的任何方式。