Both ConcurrentHashMap and Hashtable are thread safe K-V containers. This article starts with the source code, and briefly explains the implementation principle and difference between them.
Similar to HashMap, the bottom layer of concurrent HashMap is also implemented by array + linked list + red black tree, and K-V and hash are encapsulated by Node nodes.
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; volatile V val; volatile Node<K,V> next; }
val and next are decorated with volatile keyword to ensure memory visibility.
Take a look at its put() method:
final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); int binCount = 0; for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f); else { V oldVal = null; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; }
- Unlike HashMap, null key value is not allowed
- Calculate hashCode
- Determine whether to initialize
- If the current location is empty, use CAS algorithm to place nodes
- If the current hashCode = = MOVED, expand the capacity
- Use synchronized lock to place nodes in linked list or red black tree
- If the number of linked lists is greater than 8, it will be converted to red black tree
The get() method of ConcurrentHashMap does not use the synchronization lock mechanism.
After JDK 1.8, the thread safety of concurrent HashMap is realized by CAS + synchronized. High efficiency.
For HashTable, its underlying structure is array + linked list structure, and null key value is not allowed. Encapsulate K-V and hash with Entry.
Main get() and put() methods:
public synchronized V get(Object key) { Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return (V)e.value; } } return null; } 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; }
HashTable is not only inefficient for data traversal because there is no red black tree, but also has synchronized keyword in get() method, and get() and put() methods are directly added to the method. In this way, the efficiency is much lower than that of ConcurrentHashMap. So, if you want to use the K-V container in a concurrent situation, it is better to use ConcurrentHashMap.