English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about the Java ConcurrentHashMap class and its operations through examples.
The ConcurrentHashMap class provided by the Java collection framework provides a thread-safe map. That is, multiple threads can access the map at the same time without affecting the consistency of the entries in the map.
it inheritsConcurrentMap interface.
To create a concurrent hash map, we must first import the java.util.concurrent.ConcurrentHashMap package. After importing the package, we can create a concurrent hash map in Java.
//ConcurrentHashMap has capacity8and load factor 0.6 ConcurrentHashMap<Key, Value> numbers = new ConcurrentHashMap<>(8, 0.6f);
In the above code, we created a concurrent hash map named numbers.
Here,
Key - used as the unique identifier to associate each element (value) in the map
Value - the element associated with the key in the map
Note the statement new ConcurrentHashMap<>(8, 0.6) Here, the first parameter iscapacity, the second parameter isloadFactor.
capacity -The capacity of this mapping is8. This means that it can store8entries.
loadFactor-The load factor of this map is 0.6. This means that as long as our hash table is filled60%, the entry will be moved to a new hash table whose size is twice the size of the original hash table.
Default capacity and load factor
It is not necessary to define its capacity and load factor to create a concurrent hash map. For example,
// ConcurrentHashMap with default capacity and load factor ConcurrentHashMap<Key, Value> numbers1 = new ConcurrentHashMap<>();
By default,
The capacity of the map will be 16
The load factor will be 0.75
This is how we create a concurrent hash map containing all elements of other mappings.
import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; class Main { public static void main(String[] args) { // Create even number hashmap HashMap<String, Integer> evenNumbers = new HashMap<>(); evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); System.out.println("HashMap: {" + evenNumbers); //Create a concurrent hashmap from other mappings ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(evenNumbers); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); } }
Output result
HashMap: {Four=4, Two=2} ConcurrentHashMap: {Four=4, Two=2, Three=3}
The ConcurrentHashMap class provides methods that allow us to perform various operations on the mapping.
put() - Insert the specified key/Value mapping is inserted into the mapping
putAll() - Insert all entries of the specified mapping into this map
putIfAbsent() - If the mapping does not contain the specified key, then insert the specified key/Value mapping is inserted into the map
For example,
import java.util.concurrent.ConcurrentHashMap; class Main { public static void main(String[] args) { //Creating even number ConcurrentHashMap ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>(); // Using put() evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); // Using putIfAbsent() evenNumbers.putIfAbsent("Six", 6); System.out.println("Even number ConcurrentHashMap: {" + evenNumbers); //Creating ConcurrentHashMap of numbers ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(); numbers.put("One", 1); // Using putAll() numbers.putAll(evenNumbers); System.out.println("ConcurrentHashMap number: {" + numbers); } }
Output result
Even number ConcurrentHashMap: {Six=6, Four=4, Two=2} ConcurrentHashMap's numbers are: {Six=6, One=1, Four=-4, Two=2}
1.Using entrySet(), keySet() and values()
entrySet() - Returns a set of all keys/Collection of value mappings
keySet() - Returns a collection of all keys in the map
values() - Returns a collection of all values in the map
For example,
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); // Using entrySet() System.out.println("Key/Value mapping: " + numbers.entrySet()); // Using keySet() System.out.println("Keys: " + numbers.keySet()); // Using values() System.out.println("Values: " + numbers.values()); } }
Output result
ConcurrentHashMap: {One=1, Two=2, Three=3} Key/Value mapping: [One=1, Two=2, Three=3] Keys: [One, Two, Three] Values: [1, 2, 3]
2.Using get() and getOrDefault()
get() - Returns the value associated with the specified key. If the key is not found, it returns null.
getOrDefault() - Returns the value associated with the specified key. If the key is not found, it returns the specified default value.
For example,
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); // Using get() int value1 = numbers.get("Three"); System.out.println("Using get(): " + value1); // Using getOrDefault() int value2 = numbers.getOrDefault("Five", 5); System.out.println("Using getOrDefault(): " + value2); } }
Output result
ConcurrentHashMap: {One=1, Two=2, Three=3} Using get(): 3 Using getOrDefault(): 5
remove(key) - Returns and removes the entry associated with the specified key from the map
remove(key, value) - An entry is removed from the map only when the specified key maps to the specified value and returns a boolean value
For example,
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); //Single parameter removal method int value = numbers.remove("Two"); System.out.println("The value removed: " + value); // method with two parameters boolean result = numbers.remove("Three", 3); System.out.println("Entry {Three=")}3} Was deleted? " + result); System.out.println("Updated ConcurrentHashMap: ", + numbers); } }
Output result
ConcurrentHashMap: {One=1, Two=2, Three=3} Deleted value: 2 Entry {Three=3} Was deleted? True Updated ConcurrentHashMap: {One=1}
The ConcurrentHashMap class provides different batch operation methods that can be safely applied to the map in parallel.
The forEach() method traverses our entries and executes the specified function.
It contains two parameters.
parallelismThreshold -It specifies how many elements in the map to perform operations in parallel after.
transformer -This will convert the data before passing it to the specified function.
For example,
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); //forEach() does not include the passed function numbers.forEach(4, (k, v) -> System.out.println("key: ", + k + " value: " + v)); // forEach() passes the specified function System.out.print("Values are "); numbers.forEach(4, (k, v) -> v, (v) -> System.out.print(v + , ") } }
Output result
ConcurrentHashMap: {One = 1, Two = 2, Three = 3} key: One value: 1 key: Two value: 2 key: Three value: 3 Values are 1, 2, 3,
In the above program, we used the parallel threshold4. This means that if the map contains4entries, the operation will be executed in parallel.
variations of the forEach() method
forEachEntry() - executes the specified function for each entry
forEachKey() - executes the specified function for each key
forEachValue() - executes the specified function for each value
The search() method searches the map based on the specified function and returns the matching entry.
Here, the specified function determines what entry is searched.
It also includes an optional parameter parallelThreshold. The parallel threshold specifies how many elements in the map after which the operation is executed in parallel.
For example,
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); // using search() String key = numbers.search(4, (k, v) -> {return v == 3 ? k: null;}); System.out.println("The searched value: ", + key); } }
Output result
ConcurrentHashMap: {One=1, Two=2, Three=3} The searched value: Three
Variants of the search() method
searchEntries() - The search function is applied to keys/Value mapping
searchKeys() - The search function is only applied to keys
searchValues() - The search function is only applied to values
The reduce() method accumulates (aggregates) each entry in the map. When we need all entries to perform a common task (such as adding all values in the map), we can use this method.
It contains two parameters.
parallelismThreshold -It specifies how many elements after, the map operation will be executed in parallel.
transformer - This will transform the data before it is passed to the specified function.
For example,
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); // using search() int sum = numbers.reduce(4, (k, v) -> v, (v1, v2) -> v1 + v2); System.out.println("The sum of all values: " + sum); } }
Output result
ConcurrentHashMap: {One=1, Two=2, Three=3} The sum of all values: 6
In the above program, please note the following statements
numbers.reduce(4, (k, v) -> v, (v1, v2) -> v1+v2);
Here,
4 Is the parallel threshold
(k, v) -> v is a transformation function. It transforms the key/Value mapping is only converted to values.
(v1, v2) -> v1+v2 It is a size calculation function. It collects all values and adds them together.
A variant of the reduce() method
reduceEntries() - Returns the result of collecting all entries using the specified reducer function
reduceKeys() - Returns the result of collecting all keys using the specified reducer function
reduceValues() - Return the result of collecting all values using the specified reducer function.
The following is ConcurrentHashMap andHashMapThere are some differences between
ConcurrentHashMap isThread-safeCollections. That is, multiple threads can access and modify it at the same time.
ConcurrentHashMap provides methods for batch operations such as forEach(), search(), and reduce().
The ConcurrentHashMap class allows multiple threads to perform concurrent modification operations.
By default, concurrent hash maps are divided16Section. That is why it is allowed16The reason for multiple threads to modify the map at the same time.
The putIfAbsent() method will not overwrite the entry in the map if the specified key already exists.