Different users select same key in java hashmap at same time will it be thread safe?

I have a function working in java such that HashMap has a store of key as String and value as ArrayList. So my quetion is when different user login at the same time and they try to access the webapplication and will selecet the same key , than in that case hashmap need to be synchronized ?

like ..When User1 will login the vlaue in hashmap will store behind the scene such as map.put(A, List1) map.put(B, List2)

When User2 will login the vlaue in hashmap will store behind the scene such as map.put(A, List3) map.put(C, List4)

so now if both user will login at the same time and key is same but (List values are always different ) than this hashmap need to be synchronized ??.

Jon Skeet
people
quotationmark

Regardless of whether you're using the same key, HashMap simply isn't thread safe for any writing:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

Even if there are different keys involved, two operations at the same time could both trigger internal map expansion, leading to problems. (Or even if there's one write operation and one read operation, if the write operation adds or removes a key, that could throw off the read operation.)

Options:

EDIT: If in fact it turns out you don't have multiple threads concurrently modifying the map (because you have one map per user) then most of the issue goes away... although if there could still be multiple threads accessing the map (just not at the same time) I'd be tempted to use a concurrent map anyway to avoid issues of stale reads etc.

people

See more on this question at Stackoverflow