Peta serentak Java

Dalam tutorial ini, kita akan belajar mengenai kelas Java ConcurrentHashMap dan operasinya dengan bantuan contoh.

The ConcurrentHashMapkelas rangka koleksi Java menyediakan peta thread selamat. Maksudnya, beberapa utas dapat mengakses peta sekaligus tanpa mempengaruhi konsistensi entri dalam peta.

Ia melaksanakan antara muka ConcurrentMap.

Buat Peta Bersama

Untuk membuat hashmap serentak, kita mesti mengimport java.util.concurrent.ConcurrentHashMappakej terlebih dahulu. Sebaik sahaja kami mengimport pakej, berikut adalah bagaimana kita dapat membuat hashmap serentak di Java.

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

Dalam kod di atas, kami telah membuat hashmap serentak bernama nombor.

Di sini,

  • Kunci - pengecam unik yang digunakan untuk mengaitkan setiap elemen (nilai) dalam peta
  • Nilai - elemen yang berkaitan dengan kunci dalam peta

Perhatikan bahagiannya new ConcurrentHashMap(8, 0.6). Di sini, parameter pertama adalah kapasiti dan parameter kedua adalah loadFactor .

  • kapasiti - Kapasiti peta ini adalah 8. Maksudnya, ia dapat menyimpan 8 entri.
  • loadFactor - Faktor beban peta ini ialah 0.6. Ini bermaksud, setiap kali jadual hash kami diisi sebanyak 60%, entri dipindahkan ke jadual hash baru dua kali ganda dari ukuran jadual hash asal.

Kapasiti lalai dan faktor beban

Adalah mungkin untuk membuat hashmap serentak tanpa menentukan kapasiti dan faktor muatannya. Sebagai contoh,

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

Secara lalai,

  • kapasiti peta akan menjadi 16
  • faktor beban akan menjadi 0.75

Membuat ConcurrentHashMap dari Peta Lain

Inilah caranya kita dapat membuat hashmap serentak yang mengandungi semua elemen peta lain.

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

Pengeluaran

 HashMap: (Four = 4, Two = 2) ConcurrentHashMap: (Four = 4, Two = 2, Three = 3) 

Kaedah ConcurrentHashMap

The ConcurrentHashMapkelas menyediakan kaedah yang membolehkan kita untuk melakukan pelbagai operasi di atas peta.

Masukkan Elemen ke ConcurrentHashMap

  • put() - memasukkan pemetaan kunci / nilai yang ditentukan ke peta
  • putAll() - memasukkan semua entri dari peta yang ditentukan ke peta ini
  • putIfAbsent() - memasukkan pemetaan kunci / nilai yang ditentukan ke peta jika kunci yang ditentukan tidak terdapat dalam peta

Sebagai contoh,

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

Pengeluaran

 ConcurrentHashMap nombor genap: (Six = 6, Four = 4, Two = 2) ConcurrentHashMap nombor: (Enam = 6, Satu = 1, Empat = -4, Dua = 2) 

Akses Elemen ConcurrentHashMap

1. Menggunakan entrySet (), keySet () dan nilai ()

  • entrySet() - mengembalikan sekumpulan semua pemetaan kunci / nilai peta
  • keySet() - mengembalikan sekumpulan semua kunci peta
  • values() - mengembalikan sekumpulan semua nilai peta

Sebagai contoh,

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

Pengeluaran

 ConcurrentHashMap: (Satu = 1, Dua = 2, Tiga = 3) Pemetaan kunci / Nilai: (Satu = 1, Dua = 2, Tiga = 3) Kekunci: (Satu, Dua, Tiga) Nilai: (1, 2, 3 ) 

2. Menggunakan get () dan getOrDefault ()

  • get()- Mengembalikan nilai yang berkaitan dengan kunci yang ditentukan. Kembali nulljika kunci tidak dijumpai.
  • getOrDefault()- Mengembalikan nilai yang berkaitan dengan kunci yang ditentukan. Mengembalikan nilai lalai yang ditentukan jika kunci tidak dijumpai.

Sebagai contoh,

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

Pengeluaran

 ConcurrentHashMap: (Satu = 1, Dua = 2, Tiga = 3) Menggunakan get (): 3 Menggunakan getOrDefault (): 5 

Buang Elemen ConcurrentHashMap

  • remove(key) - mengembalikan dan membuang entri yang berkaitan dengan kunci yang ditentukan dari peta
  • 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?

  • The ConcurrentHashMapkelas membolehkan pelbagai benang untuk mengakses penyertaan yang serentak.
  • Secara lalai, hashmap serentak dibahagikan kepada 16 segmen . Inilah sebab mengapa 16 utas dibenarkan mengubah suai peta secara serentak pada masa yang sama. Walau bagaimanapun, sebilangan besar utas dapat mengakses peta pada satu masa.
  • The putIfAbsent()kaedah tidak akan mengatasi catatan dalam peta jika kunci yang ditentukan telah wujud.
  • Ia menyediakan penyegerakannya sendiri.

Artikel menarik...