Reputation: 145
I was asked a question in an interview.. What to do If I want to store values in map like this :
key_1 --> value 1
key_2 --> value 2
key_1 --> value 3
Here if we assume both key and value is in string then we should take map like this..
Map<String,List<String>> m1 = new HashMap();
Then I was asked what if you want to achieve thread safety? Then I said we can take ConcurrentHashMap for this purpose..they said ok..
Then they asked are value I mean List is threadsafe ? Ex.
t1.get("key_1").put("value_4");
t2.get("key_1").put("value_5");
Here, assume both threads t1 and t2 are running in parallel. So if that List<String>
i mean value inside ConcurrentHashMap is Thread-Safe ? If yes then how ? and if No then how to achieve that ??
Upvotes: 1
Views: 73
Reputation: 27115
I said we can take ConcurrentHashMap for this purpose..they said ok..
Maybe it's OK, maybe not. It depends on whether there is any special relationship between key_1 and key_2.
Suppose that one thread stores a new value for key_1, and then just before it can store a related value for key_2, its time slice ends. Another thread then examines the values of key_1 and key_2 while the first thread is suspended. It sees the new value for key_1, but it sees the old value for key_2.
Does it matter at that point that the first thread was only half-way done updating the two keys?
Plugging in a ConcurrentHashMap
will ensure that the map data structure itself will not do anything funny or wrong in a multi-threaded application, but if the application depends on those two keys always being updated together, then you're still going to need some kind of explicit locking to ensure that they always are updated together.
Upvotes: 0
Reputation: 3232
ConcurrentHashMap
is Thread Safe Data Structure. If you use List<String>
(which is Not thread safe) in value of ConcurrentHashMap
then the List
is not Thread safe because two thread can safe the reference of list and later modify it parallel.
ConcurrentHashMap
is a thread safe means Its operations like put
and putAll
e.t.c are thread safe.It does't mean the data structure which you are using as its value also become Thread safe.
How to achieve that ?
List<String>
like CopyOnWriteArrayList
as value in your ConcurrentHashMap
.List
and make their all methods Synchronized
.List
to Thread safe List
by passing in Collections.synchronizedList(non-Thread safelist)
. Upvotes: 1