Thread safe implementation for Hash Map

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.

Answers


EDIT: removed false information

In any case, the synchronized keyword is a safe bet. It blocks any threads from accessing the object while inside a synchronized block.

// Anything can modify map at this point, making it not thread safe
map.get(0);

as opposed to

// Nothing can modify map until the synchronized block is complete
synchronized(map) {
    map.get(0);
}

ConcurrentHashMap.get() is thread safe.

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


Collections.synchronizedMap(new HashMap<K, V>);

Returns a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.

It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:


Need Your Help

Meteor require don't work

javascript node.js meteor require

I try to use eventEmitter in my meteor project.

UICollectionView vs. iCarousel (continuous loop, snapping, etc.)

ios uicollectionview icarousel

I need to make a collection view with a continuous loop of the contents. So, for instance, if the cell items have the integers 1 through 10, then when you hit 10, the next item in the list is 1, s...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.