Differences between HashMap and ConcurrentHashMap
HashMap has been available since JDK1.2. As mentioned in the previous article, HashMap is NOT thread-safe. Therefore, you must be extremely careful when performing multi-threaded operations.
In JDK1.5, the great Doug Lea brought us the concurrent package, and the Map was also safe.
How does ConcurrentHashMap implement thread security? It is certainly impossible to add synchronized to every method, and it becomes HashTable. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + keys/J0tS/tLP2o6zL/keys + KGxtcS4xcTuo6y + weight/WuPm + weight + Weight = "http://www.2cto.com/uploadfile/Collfiles/20141106/20141106081435254.png" alt = "\">
Test procedure:
import java.util.concurrent.ConcurrentHashMap;public class ConcurrentHashMapTest {private static ConcurrentHashMap
map = new ConcurrentHashMap
();public static void main(String[] args) {new Thread("Thread1"){@Overridepublic void run() {map.put(3, 33);}};new Thread("Thread2"){@Overridepublic void run() {map.put(4, 44);}};new Thread("Thread3"){@Overridepublic void run() {map.put(7, 77);}};System.out.println(map);}}
In ConcurrentHashMap, segments are initialized to an array with a length of 16 by default.
According to the ConcurrentHashMap. segmentFor algorithm, segments 3 and 4 are all segments [1], and 7 is segments [12].
(1) When Thread1 and Thread2 enter the Segment. put Method successively, Thread1 will first obtain the lock and can enter, while Thread2 will block the lock:
(2) switch to Thread3 and go to the Segment. put method. Because the Segment stored in 7 is different from that stored in 3 and 4, it is not blocked in lock ():
The above is the working mechanism of ConcurrentHashMap. By dividing the entire Map into N segments (similar to HashTable), we can provide the same thread security, but the efficiency is improved by N times. By default, it is increased by 16 times.