繁体   English   中英

使用哪一个:HashMap 和 ConcurrentHashMap with Future values JAVA?

[英]Which one to use: HashMap and ConcurrentHashMap with Future values JAVA?

基本上我们倾向于在多线程环境中使用 ConcuttentHashMap。 我目前的代码是这样的:

ExecutorService executor = Executors.newFixedThreadPool(3);
Map<String, Future<String>> myMap = new HashMap<String, Future<String>>();
myMap.put("SomeValue", executor.submit(() -> return callAndReturnStringMethod("SomeValue"));
myMap.put("AnotheValue", executor.submit(() -> return callAndReturnStringMethod("AnotheValue"));
...
....

我只想存储与传递的 String 作为映射中的 Key 对应的异步线程调用的未来对象。

我的第一个问题:在处理 Future 对象时使用 HashMap 而不是 ConcurrentHashMap 会好吗? 在这种情况下我应该使用 ConcurrentHashMap 吗? 第二个问题:如果我使用后一个,会有什么取舍?

你这么说

地图值没有得到修改。

所以应该没有理由选择 ConcurrentHashMap。 ConcurrentHashMap 旨在提供跨线程操作的线程安全性和原子性,您都不需要。

权衡是当您不需要线程安全/原子操作时,您要为它们付出代价。 至于实际是多少,这取决于您的应用程序。

相关主题

两者都不。

使用EnumMap并将您的SomeValue/AnotherValueenum 构建速度更快,搜索速度更快,存储更紧凑。 如果您不打算同时更改ConcurrentHashMap本身,我认为使用任何并发数据结构的理由为零。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM