Interview question: How ConcurrentHashMap implements thread safety

Before ConcurrentHashMap did not appear, jdk used hashtable to achieve thread safety, but hashtable locks the entire hash table, so the efficiency is very low.

ConcurrentHashMap puts data into multiple segments, 16 by default , and each segment contains multiple arrays of HashEntry lists.

For a key, it takes three hash operations to finally locate the position of the element. The three hashes are:

  1. For a key, perform a hash operation first to get the hash value h1 , that is, h1 = hash1(key);
  2. Perform a second hash on the high bits of the obtained h1 to get the hash value h2, that is, h2 = hash2 (higher bits of h1), and the segment where the element is placed can be determined by h2;
  3. The obtained h1 is hashed for the third time, and the hash value h3 is obtained, that is, h3 = hash3(h1), which can determine which HashEntry the element is placed in through h3.

Each segment has a lock. When a write operation is performed, only one segment needs to be locked, and the data in other segments can be accessed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325369252&siteId=291194637