Sahil
Sahil

Reputation: 9478

Why do we need lock in the put methods of Hashtable/ConcurrentHashMap?

I am trying to understand the functioning of Hashtable/Concurrent HashMap in multithreaded environment. I can't figure out why make the put method of hashtable synchronized.

For instance, if there are multiple threads trying to set value for a particular key, we do we need to use locks, why can't we perform the operations without the locks? At worst, the threads will overwrite each other's data, which technically seems right to me.

What am I missing here? Why do we need to get locks invovled?

Upvotes: 2

Views: 737

Answers (2)

Stu Stephenson
Stu Stephenson

Reputation: 153

For instance, if there are multiple threads trying to set value for a particular key, we do we need to use locks, why can't we perform the operations without the locks?

Locks ensure that the hashtable is only updated by one thread at a time. If 2 puts were called concurrently, there could be 2 puts trying to add the same key and value at the same time which would cause an error (Hashtable.put is an UPSERT rather than UPDATE). Locking stops this occurring as one key is added by the first thread and the second key by the second.

Upvotes: 0

M A
M A

Reputation: 72874

Here is the code of Hashtable.put (JDK 11):

public synchronized V put(K key, V value) {
    // Make sure the value is not null
    if (value == null) {
        throw new NullPointerException();
    }

    // Makes sure the key is not already in the hashtable.
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> entry = (Entry<K,V>)tab[index];
    for(; entry != null ; entry = entry.next) {
        if ((entry.hash == hash) && entry.key.equals(key)) {
            V old = entry.value;
            entry.value = value;
            return old;
        }
    }

    addEntry(hash, key, value, index);
    return null;
}

Assuming it was not synchronized, what happens if two threads are calling put on the same key, and they reached the line calling addEntry (after looping over all entries and not finding one with the key)? Bad things may happen, for example, the field count (number of entries) will be increased twice for the same key.

Upvotes: 3

Related Questions