📜  ConcurrentHashMap 和 SynchronizedHashMap 的区别

📅  最后修改于: 2021-09-13 03:01:04             🧑  作者: Mango

ConcurrentHashMap 和 SynchronizedHashMap 都是 Collection 类,它们是线程安全的,可用于多线程和并发Java应用程序。但是它们之间几乎没有区别。在本文中,我们试图涵盖它们之间的所有这些差异。

1. ConcurrentHashMap : ConcurrentHashMap 是一个实现ConcurrentMap 接口的类。它用 哈希表带下划线的数据结构。众所周知,在我们的应用程序HashMap 中处理线程时 由于性能问题,这不是一个好的选择。为了解决这个问题,我们在我们的应用程序中使用 ConcurrentHashMap。 ConcurrentHashMap 是线程安全的,因此多个线程可以对单个对象进行操作而不会出现任何问题。在 ConcurrentHashMap 中,Object 根据并发级别分为多个段。默认情况下,它允许 16 个线程从Map 中读取和写入 没有任何同步。在 ConcurrentHashMap 中,一次可以有任意数量的线程执行检索操作,但是为了在对象中进行更新,线程必须锁定线程想要操作的特定段。这种类型的锁定机制称为段锁定或存储桶锁定。因此,线程可以一次执行 16 个更新操作。

ConcurrentHashMap 演示:

Java
// Java Program to demonstrate the
// working of ConcurrentHashMap
  
import java.util.*;
import java.util.concurrent.*;
  
public class TraversingConcurrentHashMap {
  
    public static void main(String[] args)
    {
  
        // create an instance of ConcurrentHashMap
        ConcurrentHashMap chmap
            = new ConcurrentHashMap();
  
        // Add elements using put()
        chmap.put(10, "Geeks");
        chmap.put(20, "for");
        chmap.put(30, "Geeks");
        chmap.put(40, "Welcome");
        chmap.put(50, "you");
  
        // Create an Iterator over the
        // ConcurrentHashMap
        Iterator >
            itr = chmap.entrySet().iterator();
  
        // The hasNext() method is used to check if there is
        // a next element and the next() method is used to
        // retrieve the next element
        while (itr.hasNext()) {
            ConcurrentHashMap.Entry entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}


Java
// Java program to demonstrate the
// working of Synchronized HashMap
  
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
  
public class SynchronizedHashMap {
    public static void main(String args[])
    {
  
        // Creating a HashMap
        HashMap hmap
            = new HashMap();
  
        // Adding the elements using put method
        hmap.put(10, "Geeks");
        hmap.put(20, "for");
        hmap.put(30, "Geeks");
        hmap.put(25, "Welcome");
        hmap.put(40, "you");
  
        // Creating a synchronized map
        Map map = Collections.synchronizedMap(hmap);
        Set set = map.entrySet();
  
        // Synchronize on HahMap, not on set
        synchronized (map)
        {
            Iterator i = set.iterator();
            // Printing the elements
            while (i.hasNext()) {
                Map.Entry me = (Map.Entry)i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            }
        }
    }
}


输出
Key = 50, Value = you
Key = 20, Value = for
Key = 40, Value = Welcome
Key = 10, Value = Geeks
Key = 30, Value = Geeks

2、同步HashMap: Java HashMap是一个非同步的集合类。如果我们需要对它执行线程安全操作,那么我们必须显式地同步它。 Java.util.CollectionssynchronizedMap()方法用于同步它。它返回由指定映射支持的同步(线程安全)映射。

同步HashMap演示:

Java

// Java program to demonstrate the
// working of Synchronized HashMap
  
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
  
public class SynchronizedHashMap {
    public static void main(String args[])
    {
  
        // Creating a HashMap
        HashMap hmap
            = new HashMap();
  
        // Adding the elements using put method
        hmap.put(10, "Geeks");
        hmap.put(20, "for");
        hmap.put(30, "Geeks");
        hmap.put(25, "Welcome");
        hmap.put(40, "you");
  
        // Creating a synchronized map
        Map map = Collections.synchronizedMap(hmap);
        Set set = map.entrySet();
  
        // Synchronize on HahMap, not on set
        synchronized (map)
        {
            Iterator i = set.iterator();
            // Printing the elements
            while (i.hasNext()) {
                Map.Entry me = (Map.Entry)i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            }
        }
    }
}
输出
20: for
40: you
25: Welcome
10: Geeks
30: Geeks

ConcurrentHashMap 和 Synchronized HashMap 的区别:

                  ConcurrentHashMap

                      Synchronized HashMap

ConcurrentHashMap is a class that implements the ConcurrentMap and serializable interface. We can synchronize the HashMap by using the synchronizedMap() method of java.util.Collections class.
It locks some portion of the map. It locks the whole map.
ConcurrentHashMap allows performing concurrent read and write operation. Hence, performance is relatively better than the Synchronized Map. In Synchronized HashMap, multiple threads can not access the map concurrently. Hence, the performance is relatively less than the ConcurrentHashMap.
ConcuurentHashMap doesn’t allow inserting null as a key or value. Synchronized HashMap allows inserting null as a key.
ConccurentHashMap doesn’t throw ConcurrentModificationException. Synchronized HashMap throw ConcurrentModificationException.