开发者

ConcurrentHashMap with ArrayList as value

开发者 https://www.devze.com 2023-03-04 05:08 出处:网络
I need to use a HashMap of the form <String, ArrayList<String>> that is going to be accessed by several different threads. From what I\'ve managed to understand, ConcurrentHashMap is the

I need to use a HashMap of the form <String, ArrayList<String>> that is going to be accessed by several different threads. From what I've managed to understand, ConcurrentHashMap is the preferred method. But will there be any problem wit开发者_如何学运维h the fact that the value of the map is an ArrayList? Do I have to define the value as a synchronized ArrayList or something like that?


yes, there can be a problem. The ConcurrentHashMap will be thread safe for accesses into the Map, but the Lists served out need to be thread-safe, if multiple threads can operate on the same List instances concurrently.

So use a thread-safe list if that is true.

Edit -- now that i think about it, the rabbit-hole goes further. You have your Map, you have your List, and you have the objects in the list. Anything multiple threads can modify should be thread safe. So if many threads can modify the Map, Lists, and Objects in the Lists, then all of those should have thread-safety guards. If only the Map and List instances can be modified concurrently, only they need thread safety. If multiple threads can read everything, but not modify, then you don't need any thread safety (I think, someone will correct me if this is wrong)


ConcurrentHashMap guarantees atomicity in its mutating methods e.g. putIfAbsent, computeIfAbsent, computeIfPresent so if all the modification is done through these methods no problems will arise.

But at the same time, multiple threads can read the same map entry (concurrent reads are allowed). therefore multiple threads can access and modify an unsafe collection (map value)

0

精彩评论

暂无评论...
验证码 换一张
取 消