Java ConcurrentHashMap

В този урок ще научим за класа 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); 

В горния код създадохме едновременна хеш-карта с имена числа.

Тук,

  • Ключ - уникален идентификатор, използван за свързване на всеки елемент (стойност) в карта
  • Стойност - елементи, свързани с ключове в карта

Забележете частта 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 Elements

1. Използване на entrySet (), keySet () и стойности ()

  • 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: (One = 1, Two = 2, Three = 3) Съпоставяне на ключ / стойност: (One = 1, Two = 2, Three = 3) Клавиши: (One, Two, Three) Стойности: (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: (One = 1, Two = 2, Three = 3) Използване на get (): 3 Използване на getOrDefault (): 5 

Премахнете ConcurrentHashMap елементи

  • remove(key) - връща и премахва записа, свързан с посочения ключ, от картата
  • remove(key, value) - премахва записа от картата само ако посоченият ключ се съпостави с посочената стойност и върне булева стойност

Например,

 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); ) ) 

Изход

ConcurrentHashMap: (One = 1, Two = 2, Three = 3) Премахната стойност: 2 Премахнат ли е записът (Three = 3)? Вярно актуализирана ConcurrentHashMap: (One = 1)

Групови едновременни операции на HashMap

Най- ConcurrentHashMapкласа предлага различни операции насипни, които могат да се прилагат безопасно да едновременни карти.

1. Метод forEach ()

На forEach()повтаря, метод над нашите записи и изпълнява определената функция.

Той включва два параметъра.

  • parallelismThreshold - Указва, че след колко елемента се извършват паралелно операции в картата.
  • трансформатор - Това ще преобразува данните, преди данните да бъдат предадени на определената функция.

Например,

 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 + ", ")); ) ) 

Изход

 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 entry
  • forEachKey() - executes the specified function for each key
  • forEachValue() - 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 mappings
  • searchKeys() - search function is only applied to the keys
  • searchValues() - 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 function
  • reduceKeys() - returns the result of gathering all the keys using the specified reducer function
  • reduceValues() - 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 like forEach(), search() and reduce().

Why ConcurrentHashMap?

  • В ConcurrentHashMapкласа позволява множество нишки за достъп до записите си едновременно.
  • По подразбиране едновременната хеш-карта е разделена на 16 сегмента . Това е причината, поради която на 16 нишки е позволено едновременно да променят картата едновременно. Въпреки това, произволен брой нишки могат да имат достъп до картата наведнъж.
  • В putIfAbsent()метода няма да отмени влизането в картата, ако посоченият ключът вече съществува.
  • Той осигурява собствена синхронизация.

Интересни статии...