Home  >  Article  >  Java  >  How to use the ConcurrentHashMap function for concurrent mapping operations in Java

How to use the ConcurrentHashMap function for concurrent mapping operations in Java

WBOY
WBOYOriginal
2023-06-26 17:48:161028browse

With the popularity of multi-core processors, concurrent programming in computer applications has become an increasingly important skill. In Java, ConcurrentHashMap is an efficient concurrent mapping table data structure that can meet the needs of concurrent access while ensuring thread safety. This article will introduce how to use the ConcurrentHashMap function in Java to perform concurrent mapping operations.

ConcurrentHashMap is a thread-safe hash table implementation introduced in Java 5. Compared with Hashtable and SynchronizedMap, it has better concurrency performance. Similar to Hashtable and SynchronizedMap, ConcurrentHashMap is also a mapping table of key-value pairs, but it uses segmented lock technology to reduce lock competition.

Using ConcurrentHashMap in Java is simple. First, you need to import the java.util.concurrent.ConcurrentHashMap package, and then create a ConcurrentHashMap object.

import java.util.concurrent.ConcurrentHashMap;

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

In the above code, we created a ConcurrentHashMap object to store key-value pairs, where the key type is String and the value type is Integer.

Commonly used ConcurrentHashMap functions
The following are the commonly used functions in ConcurrentHashMap and how to use them.

  1. put()
    Add the specified key-value pair to ConcurrentHashMap. If the specified key already exists, the corresponding value is updated and the old value is returned. If the specified key does not exist, a new key-value pair is added and null is returned.

    Integer oldValue = map.put("a", 1); // 添加键值对a=1,返回null
    Integer value = map.put("b", 2); // 添加键值对b=2,返回null
    Integer newValue = map.put("a", 3); // 更新键值对a=3,返回旧值1
  2. get()
    Get the value corresponding to the specified key. If the key does not exist, returns null.

    Integer value = map.get("a"); // 获取键a对应的值3
  3. remove()
    Delete the specified key-value pair. If the key does not exist, returns null.

    Integer value = map.remove("a"); // 删除键a对应的键值对,返回值3
  4. replace()
    Replace the value corresponding to the specified key. If the key does not exist, returns null.

    Integer oldValue = map.replace("b", 4); // 替换键b对应的值为4,返回旧值2
  5. putIfAbsent()
    If the specified key does not exist, add a new key-value pair and return null. If the specified key already exists, the corresponding value is returned.

    Integer oldValue = map.putIfAbsent("a", 5); // putIfAbsent会判断键a是否存在,因为键a已经存在于ConcurrentHashMap中,此次添加操作不会执行,返回a对应的旧值3
    Integer value = map.putIfAbsent("c", 6); // putIfAbsent会判断键c是否存在,因为键c不存在于ConcurrentHashMap中,此次添加键值对c=6操作会执行,返回null
  6. size()
    Get the number of key-value pairs in ConcurrentHashMap.

    int size = map.size(); // 获取ConcurrentHashMap中键值对的数量
  7. clear()
    Delete all key-value pairs in ConcurrentHashMap.

    map.clear(); // 删除ConcurrentHashMap中的所有键值对

Sample code
The following is a simple example showing how to use the ConcurrentHashMap function for concurrent mapping operations. In this example, we will start multiple threads to add key-value pairs to ConcurrentHashMap and access the key-value pairs simultaneously.

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapDemo {
    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        // 添加键值对的线程
        Thread addThread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                map.put(String.valueOf(i), i);
            }
        });

        // 访问键值对的线程
        Thread visitThread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                Integer value = map.get(String.valueOf(i));
                System.out.println(Thread.currentThread().getName() + " " + value);
            }
        });

        addThread.start();
        visitThread.start();

        addThread.join();
        visitThread.join();
    }
}

In this example, we start two threads, one thread is used to add key-value pairs to ConcurrentHashMap, and the other thread is used to access key-value pairs. In the access thread, we use the get() function of ConcurrentHashMap to obtain the value of the key-value pair.

The output results are as follows:

Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
.
.
.
Thread-1 97
Thread-1 98
Thread-1 99

It can be seen that the adding thread and the access thread run at the same time, and there will be no competition between threads. ConcurrentHashMap ensures thread safety and high concurrency performance.

Summary
This article introduces how to use the ConcurrentHashMap function for concurrent mapping operations in Java. By using ConcurrentHashMap, we can improve the concurrency performance of the program and ensure thread safety in multi-threaded scenarios. Whether you are developing high-concurrency network applications or distributed systems that process large-scale data, ConcurrentHashMap is a very practical tool.

The above is the detailed content of How to use the ConcurrentHashMap function for concurrent mapping operations in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn