Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ConcurrentHashMap, when is synchronizing necessary?

I have a ConcurrentHashMap where I do the following:

sequences = new ConcurrentHashMap<Class<?>, AtomicLong>();

if(!sequences.containsKey(table)) {
    synchronized (sequences) {
        if(!sequences.containsKey(table))
            initializeHashMapKeyValue(table);
    }
}

My question is - is it unnecessary to make the extra

if(!sequences.containsKey(table))

Check inside the synschronized block so other threads wont initialize the same hashmap value?

Maybe the check is necessary and I am doing it wrong? It seems a bit silly what I'm doing, but I think it is necessary.

like image 955
Per Stilling Avatar asked Feb 13 '13 10:02

Per Stilling


People also ask

Do I need to use synchronize for ConcurrentHashMap?

ConcurrentHashMap is thread-safe therefore multiple threads can operate on a single object without any problem. In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level. By default, it allows 16 thread to read and write from the Map without any synchronization.

How does synchronization work in ConcurrentHashMap?

Each method is synchronized using an object level lock . So the get and put methods on synchMap acquire a lock. Locking the entire collection is a performance overhead. While one thread holds on to the lock, no other thread can use the collection.

Why is synchronization necessary in multithreaded programming?

We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource. If an Object is shared by multiple threads then there is need of synchronization in order to avoid the Object's state to be getting corrupted. Synchronization is needed when Object is mutable.

What is the purpose to use synchronization?

The main purpose of synchronization is the sharing of resources without interference using mutual exclusion. The other purpose is the coordination of the process interactions in an operating system. Semaphores and monitors are the most powerful and most commonly used mechanisms to solve synchronization problems.


1 Answers

All operations on a ConcurrentHashMap are thread-safe, but thread-safe operations are not composable. You trying to make atomic a pair of operations: checking for something in the map and, in case it's not there, put something there (I assume). So the answer to your questions is yes, you need to check again, and your code looks ok.

like image 150
João Fernandes Avatar answered Oct 08 '22 07:10

João Fernandes