Java ConcurrentHashMap

In questo tutorial, impareremo a conoscere la classe Java ConcurrentHashMap e le sue operazioni con l'aiuto di esempi.

La ConcurrentHashMapclasse del framework delle collezioni Java fornisce una mappa thread-safe. Cioè, più thread possono accedere alla mappa contemporaneamente senza influire sulla coerenza delle voci in una mappa.

Implementa l'interfaccia ConcurrentMap.

Crea un ConcurrentHashMap

Per creare una hashmap simultanea, dobbiamo java.util.concurrent.ConcurrentHashMapprima importare il pacchetto. Una volta importato il pacchetto, ecco come possiamo creare hashmap simultanee in Java.

 // ConcurrentHashMap with capacity 8 and load factor 0.6 ConcurrentHashMap numbers = new ConcurrentHashMap(8, 0.6f); 

Nel codice sopra, abbiamo creato una hashmap simultanea denominata numeri.

Qui,

  • Chiave: un identificatore univoco utilizzato per associare ogni elemento (valore) in una mappa
  • Valore: elementi associati da chiavi in ​​una mappa

Nota la parte new ConcurrentHashMap(8, 0.6). Qui, il primo parametro è la capacità e il secondo parametro è loadFactor .

  • capacità - La capacità di questa mappa è 8. Ciò significa che può memorizzare 8 voci.
  • loadFactor - Il fattore di carico di questa mappa è 0,6. Ciò significa che, ogni volta che la nostra tabella hash è riempita del 60%, le voci vengono spostate in una nuova tabella hash di dimensioni doppie rispetto alla tabella hash originale.

Capacità e fattore di carico predefiniti

È possibile creare una hashmap simultanea senza definirne la capacità e il fattore di carico. Per esempio,

 // ConcurrentHashMap with default capacity and load factor ConcurrentHashMap numbers1 = new ConcurrentHashMap(); 

Per impostazione predefinita,

  • la capacità della mappa sarà 16
  • il fattore di carico sarà 0,75

Creazione di ConcurrentHashMap da altre mappe

Ecco come possiamo creare una hashmap simultanea contenente tutti gli elementi di altre mappe.

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

Produzione

 HashMap: (Quattro = 4, Due = 2) ConcurrentHashMap: (Quattro = 4, Due = 2, Tre = 3) 

Metodi di ConcurrentHashMap

La ConcurrentHashMapclasse fornisce metodi che ci consentono di eseguire varie operazioni sulla mappa.

Inserisci elementi in ConcurrentHashMap

  • put() - inserisce la mappatura chiave / valore specificata nella mappa
  • putAll() - inserisce tutte le voci dalla mappa specificata a questa mappa
  • putIfAbsent() - inserisce la mappatura chiave / valore specificata nella mappa se la chiave specificata non è presente nella mappa

Per esempio,

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

Produzione

 ConcurrentHashMap di numeri pari: (Six = 6, Four = 4, Two = 2) ConcurrentHashMap di numeri: (Six = 6, One = 1, Four = -4, Two = 2) 

Accedi agli elementi ConcurrentHashMap

1. Utilizzo di entrySet (), keySet () e values ​​()

  • entrySet() - restituisce un insieme di tutte le mappature chiave / valore della mappa
  • keySet() - restituisce un insieme di tutte le chiavi della mappa
  • values() - restituisce un insieme di tutti i valori della mappa

Per esempio,

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

Produzione

 ConcurrentHashMap: (Uno = 1, Due = 2, Tre = 3) Mappature chiave / valore: (Uno = 1, Due = 2, Tre = 3) Chiavi: (Uno, Due, Tre) Valori: (1, 2, 3 ) 

2. Utilizzo di get () e getOrDefault ()

  • get()- Restituisce il valore associato alla chiave specificata. Restituisce nullse la chiave non viene trovata.
  • getOrDefault()- Restituisce il valore associato alla chiave specificata. Restituisce il valore predefinito specificato se la chiave non viene trovata.

Per esempio,

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

Produzione

 ConcurrentHashMap: (Uno = 1, Due = 2, Tre = 3) Utilizzo di get (): 3 Utilizzo di getOrDefault (): 5 

Rimuovi elementi ConcurrentHashMap

  • remove(key) - restituisce e rimuove dalla mappa la voce associata alla chiave specificata
  • 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 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?

  • La ConcurrentHashMapclasse consente a più thread di accedere alle sue voci contemporaneamente.
  • Per impostazione predefinita, la hashmap simultanea è divisa in 16 segmenti . Questo è il motivo per cui a 16 thread è consentito di modificare contemporaneamente la mappa allo stesso tempo. Tuttavia, qualsiasi numero di thread può accedere alla mappa alla volta.
  • Il putIfAbsent()metodo non sovrascriverà la voce nella mappa se la chiave specificata esiste già.
  • Fornisce la propria sincronizzazione.

Articoli interessanti...