Search code examples
javaconcurrencysynchronizationsynchronizedconcurrenthashmap

Is synchronized(hashmap.get(data)) thread safe?


Suppose that i have a java class called Foo containing one attribute that is a ConcurrentHashMap called h.

Suppose also that Foo class has 2 methods defined like this:

public void fooMethod1() {
    synchronized(this.h.get("example")) {
        ...
    }
}

public void fooMethod2() {
    synchronized(this.h.get("example")) {
        ...
    }
}

Suppose now that it's called first fooMethod1() and after fooMethod2() from 2 different threads.

I don't know if it's possible that between this.h.get("example") call in fooMethod1() and the synchronization of object returned by the above get, there can be the interleaving of this.h.get("example") call in fooMethod2().


Solution

  • I don't know if it's possible that between this.h.get("example") call in fooMethod1() and the synchronization of object returned by the above get, there can be the interleaving of this.h.get("example") call in fooMethod2().

    Yes, there could be interleaving at the point you indicate.

    The synchronized mutual exclusion is on the result of the respective get calls, not on the get calls themselves.

    So if a third thread is updating the map, the two get("example") calls could return different values, and you would not get mutual exclusion on the same map entry.

    Secondly, in the following snippet:

    synchronized(this.h.get("example")) {
        ...
    }
    

    only the code in the { ... } block gets mutual exclusion.

    A third thing to note is that this.h is not guaranteed to be thread-safe unless h has been declared as final.


    Finally, it is next to impossible to say whether this is thread-safe or not thread-safe. Thread safety is a rather difficult property to define precisely, but it informally it means that the code will behave as expected (or as specified) irrespective of the number of threads, and for all possible execution interleaving patterns.

    In your example, you don't provide enough of the code, and you don't clearly state what your expectations are.