gpt4 book ai didi

java - 使用哪一个 : HashMap and ConcurrentHashMap with Future values JAVA?

转载 作者:行者123 更新时间:2023-12-03 23:02:07 25 4
gpt4 key购买 nike

基本上我们倾向于在多线程环境中使用 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 对象。
我的第一个问题:在处理 Future 对象时使用 HashMap 而不是 ConcurrentHashMap 会好吗?在这种情况下我应该使用 ConcurrentHashMap 吗?
第二个问题:如果我使用后一个,会有什么取舍?

最佳答案

你这么说

Map values are not getting modified.


所以应该没有理由选择 ConcurrentHashMap。 ConcurrentHashMap 旨在提供跨线程操作的线程安全性和原子性,您都不需要。
权衡是,当您不需要线程安全/原子操作时,您要为它们付出代价。至于实际是多少,这取决于您的应用程序。
相关主题
  • Performance ConcurrentHashmap vs HashMap
  • Are there any drawbacks with ConcurrentHashMap?
  • 关于java - 使用哪一个 : HashMap and ConcurrentHashMap with Future values JAVA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64977478/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com