Search code examples
javasynchronizationconcurrenthashmap

Does a call to a threadsafe function need to be syncronized too?


If I'm using ConcurrentHashMap (where the put is thread safe) , and I supply a public function myPut that uses the ConcurrentHashMap put - do I need to synchronize my function?

meaning : should this be synchronized?

ConcurrentHashMap map;  
public void myPut(int something) {  
   this.map.put(something);  
}

Solution

  • Concurrency utilities such as ConcurrentHashMap are designed so that you don't need to synchronize: they'll handle thread-safe access internally.

    What Tom says is true, that you need to think about the potential of the map reference to change. If the reference actually doesn't change, then in practice you'll get away with it here: the internal synchronization of ConcurrentHashMap -- and indeed the java.util.concurrentlibrary in general -- guarantees that objects put into the map are safely published to other threads. But I would agree that even so, it is good practice to decide whether the reference can change or not, and then explicitly state this in the code ('final' if it can't; something like 'volatile' or an AtomicReference if it can).