我需要在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,并考虑一些其他填充值,而不是空值,因为并发映射不支持空值。
发布于 2018-04-10 06:54:42
您可以使用.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
}
}));选择对你更有用的东西。
https://stackoverflow.com/questions/49747070
复制相似问题