The difference between HashMap and HashTable in Java

The difference between HashMap and HashTable in Java

HashMapBoth HashTableare data structures used to store key-value pairs in Java. The main difference between them is thread safety and performance.

  1. Thread safety:
  • HashMap: It is not thread-safe, which means that in a multi-threaded environment, if multiple threads read and write the HashMapsame data at the same time , it may cause data inconsistency or concurrency exceptions. HashMapTherefore, use in a multi-threaded environment HashMaprequires additional synchronization measures (such as using Collections.synchronizedMap()or ConcurrentHashMap) to ensure thread safety.
  • HashTable: HashTableis thread-safe, all its methods are synchronized, and the internal implementation uses synchronizedkeywords to synchronize methods. This means that in a multi-threaded environment, HashTableread and write operations can be performed safely without data inconsistency.
  1. performance:
  • HashMap: Because HashMapit is non-thread-safe, its performance in a single-threaded environment is usually HashTableslightly better than . Because HashMapno additional synchronization operations are required, it performs faster. However, in a highly concurrent multi-threaded environment, HashMapperformance may degrade due to the need for additional synchronization measures.
  • HashTable: Since HashTableit is thread-safe, its performance in multi-threaded environments may be affected. Since all methods are synchronized, multiple threads HashTablewill compete for locks when accessing at the same time, resulting in performance degradation.

To sum up, in a multi-threaded environment, if you need to ensure data consistency and thread safety, you can choose to use it HashTable. But in a single-threaded environment or when thread safety does not need to be considered, it HashMapwill usually HashTablehave better performance.

However, it should be noted that starting from Java 1.7, a ConcurrentHashMapthread-safe hash table implementation is also provided, and the performance ratio is better in high concurrency environments , so it is recommended to use it HashTableinstead in most cases .ConcurrentHashMapHashTable

Below is a simple Java code example that demonstrates the use of HashMapand HashTableand their different behavior in a multi-threaded environment.

import java.util.HashMap;
import java.util.Hashtable;

public class MapExample {
    
    

    public static void main(String[] args) {
    
    
        // 使用HashMap
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");

        // 使用HashTable
        Hashtable<Integer, String> hashTable = new Hashtable<>();
        hashTable.put(1, "One");
        hashTable.put(2, "Two");
        hashTable.put(3, "Three");

        // 多线程环境下对HashMap进行操作
        Runnable hashMapRunnable = () -> {
    
    
            for (int i = 4; i <= 6; i++) {
    
    
                hashMap.put(i, "Value " + i);
            }
        };

        // 多线程环境下对HashTable进行操作
        Runnable hashTableRunnable = () -> {
    
    
            for (int i = 4; i <= 6; i++) {
    
    
                hashTable.put(i, "Value " + i);
            }
        };

        // 创建两个线程,并分别对HashMap和HashTable进行操作
        Thread thread1 = new Thread(hashMapRunnable);
        Thread thread2 = new Thread(hashTableRunnable);

        thread1.start();
        thread2.start();

        // 等待两个线程执行完成
        try {
    
    
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }

        // 输出HashMap中的元素
        System.out.println("HashMap:");
        for (Integer key : hashMap.keySet()) {
    
    
            System.out.println(key + ": " + hashMap.get(key));
        }

        // 输出HashTable中的元素
        System.out.println("HashTable:");
        for (Integer key : hashTable.keySet()) {
    
    
            System.out.println(key + ": " + hashTable.get(key));
        }
    }
}

In the above code, we first created one HashMapand one respectively HashTableand added three key-value pairs to them. Then, we created two threads to add operations to HashMapand respectively. HashTableIn this way, in a multi-threaded environment, two threads will operate on HashMapand at the same time.HashTable

Because HashMapit is not thread-safe, when two threads HashMapwrite to it at the same time, data inconsistency or concurrency exceptions may occur. It isHashTable thread-safe, and all its methods are synchronized, so read and write operations can be performed safely in a multi-threaded environment.

The output results may vary depending on the order of execution, but you will find that some key-value pairs may be missing in the output results. This is due to concurrent modifications HashMapin a multi-threaded environment, resulting in data inconsistency. HashMapThe HashTableoutput result is always complete because it is thread-safe and can correctly handle multi-threaded concurrent operations.

It should be noted that although HashTableit is thread-safe, because all its methods are synchronized, it may cause performance degradation in high concurrency environments. Therefore, in Java 1.7 and later, it is recommended to use a ConcurrentHashMapthread-safe hash table implementation, which performs better in high-concurrency environments.

Guess you like

Origin blog.csdn.net/QYgujingjing/article/details/131987727