basically we tend to use ConcuttentHashMap in multi-threading environment. 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.
My first question: Will it be good to use HashMap and not ConcurrentHashMap while dealing with Future object? Should I use ConcurrentHashMap in this scenario? 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 is meant to provide thread-safety and atomicity of operations across threads, which neither you are needing.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.