Thread safe implementation for Hash Map

pratnala picture pratnala · Aug 1, 2013 · Viewed 14.6k times · Source

First, I'll describe what I want and then I'll elaborate on the possibilities I am considering. I don't know which is the best so I want some help.

I have a hash map on which I do read and write operations from a Servlet. Now, since this Servlet is on Tomcat, I need the hash map to be thread safe. Basically, when it is being written to, nothing else should write to it and nothing should be able to read it as well.

I have seen ConcurrentHashMap but noticed its get method is not thread-safe. Then, I have seen locks and something called synchronized.

I want to know which is the most reliable way to do it.

Answer

Peter Lawrey picture Peter Lawrey · Aug 1, 2013

ConcurrentHashMap.get() is thread safe.

You can make HashMap thread safe by wrapping it with Collections.synchronizedMap().