Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap with ArrayList as value

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 with 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?

like image 898
Moshe Avatar asked May 07 '11 19:05

Moshe


1 Answers

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)

like image 74
hvgotcodes Avatar answered Oct 28 '22 11:10

hvgotcodes