简体   繁体   English

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

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

basically we tend to use ConcuttentHashMap in multi-threading environment.基本上我们倾向于在多线程环境中使用 ConcuttentHashMap。 My current code is like this:我目前的代码是这样的:

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"));
...
....

I just want to store the future object for the async thread calls corresponding to the passed String as Key in the map.我只想存储与传递的 String 作为映射中的 Key 对应的异步线程调用的未来对象。

My first question: Will it be good to use HashMap and not ConcurrentHashMap while dealing with Future object?我的第一个问题:在处理 Future 对象时使用 HashMap 而不是 ConcurrentHashMap 会好吗? Should I use ConcurrentHashMap in this scenario?在这种情况下我应该使用 ConcurrentHashMap 吗? Second question: What could be the trade offs if I use latter one?第二个问题:如果我使用后一个,会有什么取舍?

You're saying that你这么说

Map values are not getting modified.地图值没有得到修改。

so there should be no reason to choose ConcurrentHashMap.所以应该没有理由选择 ConcurrentHashMap。 ConcurrentHashMap is meant to provide thread-safety and atomicity of operations across threads, which neither you are needing. ConcurrentHashMap 旨在提供跨线程操作的线程安全性和原子性,您都不需要。

The tradeoffs are that you're paying the price for thread-safe/atomic operations when you don't need them.权衡是当您不需要线程安全/原子操作时,您要为它们付出代价。 As to how much that actually is, it depends on your app.至于实际是多少,这取决于您的应用程序。

Related threads相关主题

Neither.两者都不。

Use an EnumMap and transform your SomeValue/AnotherValue to enum s.使用EnumMap并将您的SomeValue/AnotherValueenum It will be faster to build, faster to search and more compact to store.构建速度更快,搜索速度更快,存储更紧凑。 I see zero reasons to use any concurrent data structure if you do not plan to alter the ConcurrentHashMap itself , concurrently.如果您不打算同时更改ConcurrentHashMap本身,我认为使用任何并发数据结构的理由为零。

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

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