Differences between HashMap and ConcurrentHashMap

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.