使用哪一个:具有未来值 JAVA 的 HashMap 和 ConcurrentHashMap?
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"));
...
....
我只想将与传递的字符串对应的异步线程调用的未来对象存储为映射中的键。
我的第一个问题:在处理 Future 对象时使用 HashMap 而不是 ConcurrentHashMap 好吗?在这种情况下我应该使用 ConcurrentHashMap 吗?
第二个问题:如果我使用后一个,会有什么取舍?
你是说
Map values are not getting modified.
所以应该没有理由选择ConcurrentHashMap。 ConcurrentHashMap 旨在提供跨线程操作的线程安全性和原子性,而您都不需要这些。
权衡是您在不需要时为 thread-safe/atomic 操作付出代价。具体多少,要看你的app了。
相关话题
- Performance ConcurrentHashmap vs HashMap
- Are there any drawbacks with ConcurrentHashMap?
都没有。
使用 EnumMap
并将您的 SomeValue/AnotherValue
转换为 enum
。构建速度更快,搜索速度更快,存储更紧凑。如果您不打算同时更改 ConcurrentHashMap
本身 ,我认为使用任何并发数据结构的理由为零。
基本上我们倾向于在多线程环境下使用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"));
...
....
我只想将与传递的字符串对应的异步线程调用的未来对象存储为映射中的键。
我的第一个问题:在处理 Future 对象时使用 HashMap 而不是 ConcurrentHashMap 好吗?在这种情况下我应该使用 ConcurrentHashMap 吗? 第二个问题:如果我使用后一个,会有什么取舍?
你是说
Map values are not getting modified.
所以应该没有理由选择ConcurrentHashMap。 ConcurrentHashMap 旨在提供跨线程操作的线程安全性和原子性,而您都不需要这些。
权衡是您在不需要时为 thread-safe/atomic 操作付出代价。具体多少,要看你的app了。
相关话题
- Performance ConcurrentHashmap vs HashMap
- Are there any drawbacks with ConcurrentHashMap?
都没有。
使用 EnumMap
并将您的 SomeValue/AnotherValue
转换为 enum
。构建速度更快,搜索速度更快,存储更紧凑。如果您不打算同时更改 ConcurrentHashMap
本身 ,我认为使用任何并发数据结构的理由为零。