В этом руководстве мы узнаем о классе Java ConcurrentHashMap и его операциях с помощью примеров.
ConcurrentHashMap
Класс рамках коллекции Java обеспечивает поточно-карту. То есть несколько потоков могут получить доступ к карте одновременно, не влияя на согласованность записей на карте.
Он реализует интерфейс ConcurrentMap.
Создать ConcurrentHashMap
Чтобы создать параллельную хэш-карту, мы должны java.util.concurrent.ConcurrentHashMap
сначала импортировать пакет. После импорта пакета вот как мы можем создавать параллельные хэш-карты в Java.
// ConcurrentHashMap with capacity 8 and load factor 0.6 ConcurrentHashMap numbers = new ConcurrentHashMap(8, 0.6f);
В приведенном выше коде мы создали параллельную хэш-карту с именем numbers.
Вот,
- Ключ - уникальный идентификатор, используемый для связи каждого элемента (значения) на карте.
- Значение - элементы, связанные ключами на карте
Обратите внимание на деталь new ConcurrentHashMap(8, 0.6)
. Здесь первый параметр - это емкость, а второй - loadFactor .
- емкость - емкость этой карты составляет 8. Это означает, что она может хранить 8 записей.
- loadFactor - коэффициент загрузки этой карты равен 0,6. Это означает, что всякий раз, когда наша хеш-таблица заполняется на 60%, записи перемещаются в новую хеш-таблицу, размер которой в два раза превышает размер исходной хеш-таблицы.
Емкость и коэффициент загрузки по умолчанию
Можно создать параллельную хэш-карту без определения ее емкости и коэффициента загрузки. Например,
// ConcurrentHashMap with default capacity and load factor ConcurrentHashMap numbers1 = new ConcurrentHashMap();
По умолчанию,
- вместимость карты будет 16
- коэффициент загрузки составит 0,75
Создание ConcurrentHashMap из других карт
Вот как мы можем создать параллельную хэш-карту, содержащую все элементы других карт.
import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; class Main ( public static void main(String() args) ( // Creating a hashmap of even numbers HashMap evenNumbers = new HashMap(); evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); System.out.println("HashMap: " + evenNumbers); // Creating a concurrent hashmap from other map ConcurrentHashMap numbers = new ConcurrentHashMap(evenNumbers); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); ) )
Вывод
HashMap: (Четыре = 4, Два = 2) ConcurrentHashMap: (Четыре = 4, Два = 2, Три = 3)
Методы ConcurrentHashMap
ConcurrentHashMap
Класс предоставляет методы, позволяющие выполнять различные операции по карте.
Вставить элементы в ConcurrentHashMap
put()
- вставляет указанное сопоставление ключ / значение на картуputAll()
- вставляет все записи с указанной карты на эту картуputIfAbsent()
- вставляет указанное сопоставление ключа / значения на карту, если указанный ключ отсутствует на карте
Например,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( // Creating ConcurrentHashMap of even numbers ConcurrentHashMap evenNumbers = new ConcurrentHashMap(); // Using put() evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); // Using putIfAbsent() evenNumbers.putIfAbsent("Six", 6); System.out.println("ConcurrentHashMap of even numbers: " + evenNumbers); //Creating ConcurrentHashMap of numbers ConcurrentHashMap numbers = new ConcurrentHashMap(); numbers.put("One", 1); // Using putAll() numbers.putAll(evenNumbers); System.out.println("ConcurrentHashMap of numbers: " + numbers); ) )
Вывод
ConcurrentHashMap четных чисел: (Six = 6, Four = 4, Two = 2) ConcurrentHashMap чисел: (Six = 6, One = 1, Four = -4, Two = 2)
Доступ к элементам ConcurrentHashMap
1. Использование entrySet (), keySet () и values ()
entrySet()
- возвращает набор всех сопоставлений ключ / значение картыkeySet()
- возвращает набор всех ключей картыvalues()
- возвращает набор всех значений карты
Например,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( ConcurrentHashMap 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 mappings: " + numbers.entrySet()); // Using keySet() System.out.println("Keys: " + numbers.keySet()); // Using values() System.out.println("Values: " + numbers.values()); ) )
Вывод
ConcurrentHashMap: (Один = 1, Два = 2, Три = 3) Сопоставления ключей / значений: (Один = 1, Два = 2, Три = 3) Ключи: (Один, Два, Три) Значения: (1, 2, 3 )
2. Использование get () и getOrDefault ()
get()
- Возвращает значение, связанное с указанным ключом. Возвращает,null
если ключ не найден.getOrDefault()
- Возвращает значение, связанное с указанным ключом. Возвращает указанное значение по умолчанию, если ключ не найден.
Например,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( ConcurrentHashMap 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); ) )
Вывод
ConcurrentHashMap: (Один = 1, Два = 2, Три = 3) Использование get (): 3 Использование getOrDefault (): 5
Удалить элементы ConcurrentHashMap
remove(key)
- возвращает и удаляет запись, связанную с указанным ключом, с картыremove(key, value)
- removes the entry from the map only if the specified key mapped to the specified value and return a boolean value
For example,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( ConcurrentHashMap numbers = new ConcurrentHashMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); // remove method with single parameter int value = numbers.remove("Two"); System.out.println("Removed value: " + value); // remove method with two parameters boolean result = numbers.remove("Three", 3); System.out.println("Is the entry (Three=3) removed? " + result); System.out.println("Updated ConcurrentHashMap: " + numbers); ) )
Output
ConcurrentHashMap: (One=1, Two=2, Three=3) Removed value: 2 Is the entry (Three=3) removed? True Updated ConcurrentHashMap: (One=1)
Bulk ConcurrentHashMap Operations
The ConcurrentHashMap
class provides different bulk operations that can be applied safely to concurrent maps.
1. forEach() Method
The forEach()
method iterates over our entries and executes the specified function.
It includes two parameters.
- parallelismThreshold - It specifies that after how many elements operations in a map are executed in parallel.
- transformer - This will transform the data before the data is passed to the specified function.
For example,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( ConcurrentHashMap numbers = new ConcurrentHashMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("ConcurrentHashMap: " + numbers); // forEach() without transformer function numbers.forEach(4, (k, v) -> System.out.println("key: " + k + " value: " + v)); // forEach() with transformer function System.out.print("Values are "); numbers.forEach(4, (k, v) -> v, (v) -> System.out.print(v + ", ")); ) )
Output
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 have used parallel threshold 4. This means if the map contains 4 entries, the operation will be executed in parallel.
Variation of forEach() Method
forEachEntry()
- executes the specified function for each entryforEachKey()
- executes the specified function for each keyforEachValue()
- executes the specified function for each value
2. search() Method
The search()
method searches the map based on the specified function and returns the matched entry.
Here, the specified function determines what entry is to be searched.
It also includes an optional parameter parallelThreshold. The parallel threshold specifies that after how many elements in the map the operation is executed in parallel.
For example,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( ConcurrentHashMap 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("Searched value: " + key); ) )
Output
ConcurrentHashMap: (One=1, Two=2, Three=3) Searched value: Three
Variants of search() Method
searchEntries()
- search function is applied to key/value mappingssearchKeys()
- search function is only applied to the keyssearchValues()
- search function is only applied to the values
3. reduce() Method
The reduce()
method accumulates (gather together) each entry in a map. This can be used when we need all the entries to perform a common task, like adding all the values of a map.
It includes two parameters.
- parallelismThreshold - It specifies that after how many elements, operations in a map are executed in parallel.
- transformer - This will transform the data before the data is passed to the specified function.
For example,
import java.util.concurrent.ConcurrentHashMap; class Main ( public static void main(String() args) ( ConcurrentHashMap 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("Sum of all values: " + sum); ) )
Output
ConcurrentHashMap: (One=1, Two=2, Three=3) Sum of all values: 6
In the above program, notice the statement
numbers.reduce(4, (k, v) -> v, (v1, v2) -> v1+v2);
Here,
- 4 is a parallel threshold
- (k, v) -> v is a transformer function. It transfers the key/value mappings into values only.
- (v1, v2) -> v1+v2 is a reducer function. It gathers together all the values and adds all values.
Variants of reduce() Method
reduceEntries()
- returns the result of gathering all the entries using the specified reducer functionreduceKeys()
- returns the result of gathering all the keys using the specified reducer functionreduceValues()
- returns the result of gathering all the values using the specified reducer function
ConcurrentHashMap vs HashMap
Here are some of the differences between ConcurrentHashMap
and HashMap,
ConcurrentHashMap
is a thread-safe collection. That is, multiple threads can access and modify it at the same time.ConcurrentHashMap
provides methods for bulk operations likeforEach()
,search()
andreduce()
.
Why ConcurrentHashMap?
ConcurrentHashMap
Класс позволяет несколько потоков получить доступ к его записи одновременно.- По умолчанию параллельная хэш-карта разделена на 16 сегментов . Это причина, по которой 16 потоков могут одновременно изменять карту. Однако любое количество потоков может получить доступ к карте одновременно.
putIfAbsent()
Метод не отменит запись в карте , если указанный ключ уже существует.- Обеспечивает собственную синхронизацию.