2024 Didi Campus Recruitment Interview Questions Summary and Explanation (2)

4. [Basic question] Do you understand HashMap? Let’s introduce its corresponding thread-safe version.

HashMap is a collection of key-value mappings in Java, which uses a hash table to store key-value pairs. HashMap has the advantage of efficient insertion and deletion of elements, but it is not thread-safe.

ConcurrentHashMap is a thread-safe HashMap in Java that uses segmentation locks to ensure thread safety. ConcurrentHashMap has all the advantages of HashMap and is also thread-safe.

ConcurrentHashMap works by dividing the hash table into segments, and each segment is protected with a lock. When multiple threads access the same segment at the same time, locks are used to synchronize access to ensure thread safety.

The advantage of ConcurrentHashMap is that it is thread-safe and can be accessed by multiple threads at the same time. The disadvantage is that the efficiency is slightly lower than HashMap because locks need to be used to synchronize access.

Usage example of ConcurrentHashMap:

Java

import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {

  public static void main(String[] args) {
	  ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
	  map.put("a", 1);
	  map.put("b", 2);
	  map.put("c", 3);

	  System.out.println(map.get("a")); // 1
	  System.out.println(map.get("b")); // 2
	  System.out.println(map.get("c")); // 3
 

Guess you like

Origin blog.csdn.net/cq20110310/article/details/132912283