Java ConcurrentHashMap

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về lớp Java ConcurrentHashMap và các hoạt động của nó với sự trợ giúp của các ví dụ.

Các ConcurrentHashMaplớp học của khuôn khổ bộ sưu tập Java cung cấp một bản đồ thread-safe. Có nghĩa là, nhiều luồng có thể truy cập bản đồ cùng một lúc mà không ảnh hưởng đến tính nhất quán của các mục trong bản đồ.

Nó thực hiện giao diện ConcurrentMap .

Tạo một ConcurrentHashMap

Để tạo một bản đồ băm đồng thời, java.util.concurrent.ConcurrentHashMaptrước tiên chúng ta phải nhập gói. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo các bản đồ băm đồng thời trong Java.

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

Trong đoạn mã trên, chúng tôi đã tạo một bản đồ băm đồng thời có tên là các số .

Đây,

  • Key – a unique identifier used to associate each element (value) in a map
  • Value – elements associated by keys in a map

Chú ý phần new ConcurrentHashMap<>(8, 0.6). Ở đây, tham số đầu tiên là dung lượng và tham số thứ hai là loadFactor .

  • capacity – The capacity of this map is 8. Meaning, it can store 8 entries.
  • loadFactor – The load factor of this map is 0.6. This means, whenever our hash table is filled by 60%, the entries are moved to a new hash table of double the size of the original hash table.

Công suất mặc định và hệ số tải

Có thể tạo một bản đồ băm đồng thời mà không cần xác định dung lượng và hệ số tải của nó. Ví dụ,

// ConcurrentHashMap with default capacity and load factor
ConcurrentHashMap<Key, Value> numbers1 = new ConcurrentHashMap<>();

Theo mặc định,

  • the capacity of the map will be 16
  • the load factor will be 0.75

Tạo Bản đồ đồng thời từ các Bản đồ khác

Đây là cách chúng ta có thể tạo một bản đồ băm đồng thời chứa tất cả các phần tử của các bản đồ khác.

import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;

class Main {
    public static void main(String[] args) {

        // Creating a hashmap of even numbers
        HashMap<String, Integer> evenNumbers = new HashMap<>();
        evenNumbers.put("Two", 2);
        evenNumbers.put("Four", 4);
        System.out.println("HashMap: " + evenNumbers);

        // Creating a concurrent hashmap from other map
        ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(evenNumbers);
        numbers.put("Three", 3);
        System.out.println("ConcurrentHashMap: " + numbers);
    }
}

Đầu ra

HashMap: {Four=4, Two=2}
ConcurrentHashMap: {Four=4, Two=2, Three=3}

Phương thức ConcurrentHashMap

Các ConcurrentHashMaplớp học cung cấp phương pháp đó cho phép chúng tôi thực hiện các hoạt động khác nhau trên bản đồ.

Chèn các phần tử vào ConcurrentHashMap

  • put() – inserts the specified key/value mapping to the map
  • putAll() – inserts all the entries from specified map to this map
  • putIfAbsent() – inserts the specified key/value mapping to the map if the specified key is not present in the map

Ví dụ,

import java.util.concurrent.ConcurrentHashMap;

class Main {
    public static void main(String[] args) {
        // Creating ConcurrentHashMap of even numbers
        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("ConcurrentHashMap of even numbers: " + evenNumbers);

        //Creating ConcurrentHashMap of numbers
        ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
        numbers.put("One", 1);

        // Using putAll()
        numbers.putAll(evenNumbers);
        System.out.println("ConcurrentHashMap of numbers: " + numbers);
    }
}

Đầu ra

ConcurrentHashMap of even numbers: {Six=6, Four=4, Two=2}
ConcurrentHashMap of numbers: {Six=6, One=1, Four=-4, Two=2}

Truy cập các phần tử ConcurrentHashMap

1. Sử dụng entrySet (), keySet () và các giá trị ()

  • entrySet() – returns a set of all the key/value mapping of the map
  • keySet() – returns a set of all the keys of the map
  • values() – returns a set of all the values of the map

Ví dụ,

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 mappings: " + numbers.entrySet());

        // Using keySet()
        System.out.println("Keys: " + numbers.keySet());

        // Using values()
        System.out.println("Values: " + numbers.values());
    }
}

Đầu ra

ConcurrentHashMap: {One=1, Two=2, Three=3}
Key/Value mappings: [One=1, Two=2, Three=3]
Keys: [One, Two, Three]
Values: [1, 2, 3]

2. Sử dụng get () và getOrDefault ()

  • get() – Returns the value associated with the specified key. Returns null if the key is not found.
  • getOrDefault() – Returns the value associated with the specified key. Returns the specified default value if the key is not found.

Ví dụ,

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

Đầu ra

ConcurrentHashMap: {One=1, Two=2, Three=3}
Using get(): 3
Using getOrDefault(): 5

Loại bỏ các phần tử ConcurrentHashMap

  • remove(key) – returns and removes the entry associated with the specified key from the map
  • remove(key, value) – removes the entry from the map only if the specified key mapped to the specified value and return a boolean value

Ví dụ,

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

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

Đầu ra

ConcurrentHashMap: {One=1, Two=2, Three=3}
Removed value: 2
Is the entry {Three=3} removed? True
Updated ConcurrentHashMap: {One=1}

Hoạt động đồng thời hàng loạt

Các ConcurrentHashMaplớp học cung cấp số lượng lớn các hoạt động khác nhau có thể được áp dụng một cách an toàn vào các bản đồ đồng thời.

1. Phương thức forEach ()

Các forEach()lặp phương pháp trên mục và thực thi của chúng tôi các chức năng cụ thể.

Nó bao gồm hai tham số.

  • 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.

Ví dụ,

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

Đầu ra

ConcurrentHashMap: {One = 1, Two = 2, Three = 3}
key: One value: 1
key: Two value: 2
key: Three value: 3
Values are 1, 2, 3,

Trong chương trình trên, chúng tôi đã sử dụng song song ngưỡng 4 . Điều này có nghĩa là nếu bản đồ chứa 4 mục nhập, hoạt động sẽ được thực hiện song song.

Biến thể của phương thức forEach ()

  • 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. phương thức search ()

Các search()phương pháp tìm kiếm bản đồ dựa trên các chức năng cụ thể và lợi nhuận mục phù hợp.

Ở đây, hàm được chỉ định xác định mục nhập nào sẽ được tìm kiếm.

Nó cũng bao gồm một tham số tùy chọn song song Ngưỡng . Ngưỡng song song chỉ định rằng sau khi có bao nhiêu phần tử trong bản đồ thì hoạt động được thực hiện song song.

Ví dụ,

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("Searched value: " + key);

    }
}

Đầu ra

ConcurrentHashMap: {One=1, Two=2, Three=3}
Searched value: Three

Các biến thể của phương pháp tìm kiếm ()

  • 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. Phương thức Reduce ()

Các reduce()tích lũy phương pháp (quây quần bên nhau) mỗi mục trong bản đồ. Điều này có thể được sử dụng khi chúng ta cần tất cả các mục nhập để thực hiện một tác vụ chung, chẳng hạn như thêm tất cả các giá trị của bản đồ.

Nó bao gồm hai tham số.

  • 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.

Ví dụ,

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("Sum of all values: " + sum);

    }
}

Đầu ra

ConcurrentHashMap: {One=1, Two=2, Three=3}
Sum of all values: 6

Trong chương trình trên, hãy chú ý câu lệnh

numbers.reduce(4, (k, v) -> v, (v1, v2) -> v1+v2);

Đây,

  • 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.

Các biến thể của phương thức Reduce ()

  • 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 so với HashMap

Dưới đây là một số khác biệt giữa ConcurrentHashMapvà 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().

Tại sao ConcurrentHashMap?

  • Lớp ConcurrentHashMap cho phép nhiều luồng truy cập đồng thời các mục của nó.
  • Theo mặc định, bản đồ băm đồng thời được chia thành 16 đoạn. Đây là lý do tại sao 16 luồng được phép đồng thời sửa đổi bản đồ cùng một lúc. Tuy nhiên, bất kỳ số lượng chủ đề nào cũng có thể truy cập vào bản đồ tại một thời điểm.
  • Phương thức putIfAbsent () sẽ không ghi đè mục nhập trong
  • Nó cung cấp sự đồng bộ hóa của riêng nó.








Gõ tìm kiếm nhanh...