In previous articles, we introduced the tools for concurrent programming in Java: BlockingQueue interface, ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, BlockingDeque interface This is the eighth article in a series.

Because the operation method of HashMap commonly used by Java programmers is not synchronous, it will lead to inconsistent access operation data in multi-threaded environment. Another implementation class of Map interface, Hashtable, is thread-safe, but the execution efficiency is very low in multi-threaded environment. To address this issue, the thread-safe collection class ConcurrentMap was introduced in Java version 1.5.

Java. Util. Concurrent. The ConcurrentMap interface is a Java collection classes framework provides thread-safe map, which means that the multithreaded access it at the same time, will not affect the map of each data consistency. The ConcurrentMap interface has two implementation classes, ConcurrentHashMap and ConcurrentSkipListMap. The one most commonly used is ConcurrentHashMap, which we will focus on.

1. Create ConcurrentHashMap

Create a ConcurrentHashMap with the following code

// Create ConcurrentHashMap ConcurrentHashMap<Key, Value> numbers = new ConcurrentHashMap<>(8, 0.6f);Copy the code

Using the code above, we create a ConcurrentHashMap object called numbers.

  • Key – A unique identifier used to associate each element in the Map
  • Value – The Value of each element in the Map can be obtained by the key Value

Note that new ConcurrentHashMap<>(8, 0.6).

  • Capacity – The first parameter indicates that the map has a capacity of 8, meaning that the object can store 8 key-value pairs.
  • LoadFactor – the loadFactor of this map object is 0.6. This means that every time our hash table is 60% full, the entry is moved to a new hash table with twice the capacity of the original one.

We can also initialize a ConcurrentHashMap object with the following code. By default capacity=16, loadFactor=0.75

ConcurrentHashMap<Key, Value> numbers1 = new ConcurrentHashMap<>();
Copy the code

2.ConcurrentHashMap Common method

2.1. Insert elements to ConcurrentHashMap

  • put(K,V)– Inserts key/value key-value pair data into the map
  • putAll(map)– Inserts all entries from another map into the current map
  • putIfAbsent(K,V)– Inserts key/value data into the map. If the key of the key/value pair does not exist in the map, insert the data. Otherwise, no operation is performed.
import java.util.concurrent.ConcurrentHashMap; Public static void Main (String[] args) {// Create ConcurrentHashMap ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>(); // Use put() to insert data evenNumbers. Put ("Two", 2); evenNumbers.put("Four", 4); // Use putIfAbsent() to insert data evenNumbers. PutIfAbsent ("Six", 6); System.out.println(" Even set ConcurrentHashMap: "+ evenNumbers); ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(); ConcurrentHashMap<>(); numbers.put("One", 1); // Use putAll() to insert numbers. PutAll (evenNumbers); System.out.println(" ConcurrentHashMap: "+ numbers); }}Copy the code

Output result:

ConcurrentHashMap: {Six=6, Four=4, Two=2} ConcurrentHashMap: {Six=6, One=1, Four=-4, Two=2}Copy the code

2.2. Get ConcurrentHashMap elements in batches

  • entrySet()– Obtain a set of key/value pairs in the map
  • keySet()– Obtains a collection of all keys in the map
  • values()– Obtains a collection of all values in the map
import java.util.concurrent.ConcurrentHashMap; class Main { public static void main(String[] args) { ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); System.out.println(" key/value: "+ numbers.entryset ()); // Get the key/value set in the map. System.out.println(" key/value:" + numbers.entryset ()); System.out.println("Keys: "+ numbers. KeySet ()); System.out.println("Values: "+ numbers. Values ()); }}Copy the code

The output

ConcurrentHashMap: {One=1, Two=2, Three=3}
Key/Value mappings: [One=1, Two=2, Three=3]
Keys: [One, Two, Three]
Values: [1, 2, 3]
Copy the code

2.3. Get the value of the specified Key element

  • get()– Gets the value of the specified key element, or returns null if the key does not exist
  • getOrDefault()– Gets the value of the specified key element, or returns a specified default value if the key does not exist
import java.util.concurrent.ConcurrentHashMap; class Main { public static void main(String[] args) { ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); Return null int value1 = numbers. Get ("Three"); System.out.println("Using get(): " + value1); Int value2 = numbers. GetOrDefault ("Five", 5); System.out.println("Using getOrDefault(): " + value2); }}Copy the code

The output

ConcurrentHashMap: {One=1, Two=2, Three=3}
Using get(): 3
Using getOrDefault(): 5
Copy the code

2.4. Remove elements from ConcurrentHashMap

  • remove(key)– Deletes the map element based on the specified key and returns the element
  • remove(key, value)– Entries are removed from the map and a Boolean value is returned only if there is a specified key mapped to the specified value. Returning true indicates that the deletion succeeded; otherwise, the map does not contain the key-value pair.
import java.util.concurrent.ConcurrentHashMap; class Main { public static void main(String[] args) { ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); // Remove the map element according to the specified key and return the element int value = numbers. Remove ("Two"); System.out.println("Removed value: " + value); // Entries are removed from the map and a Boolean value is returned only if there is a specified key mapped to the specified value. boolean result = numbers.remove("Three", 3); System.out.println("Is the entry {Three=3} removed? " + result); System.out.println("Updated ConcurrentHashMap: " + numbers); }}Copy the code

The output

ConcurrentHashMap: {One=1, Two=2, Three=3}
Removed value: 2
Is the entry {Three=3} removed? True
Updated ConcurrentHashMap: {One=1}
Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series