Search code examples
javathread-safetyconcurrenthashmaplocks

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.


Solution

  • 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);
    }