Java ConcurrentHashMap和SynchronizedHashMap的区别
ConcurrentHashMap和SynchronizedHashMap都是线程安全的集合类,可以在多线程和并发的java应用程序中使用。但是它们之间存在着一些差异。在这篇文章中,我们试图涵盖它们之间的所有这些差异。
1. 因此,在同一时间,16个更新操作可以由线程执行。
ConcurrentHashMap演示。
// 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<Integer, String> chmap
= new ConcurrentHashMap<Integer, String>();
// 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<ConcurrentHashMap.Entry<Integer, String> >
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<Integer, String> entry
= itr.next();
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
}
输出
Key = 50, Value = you
Key = 20, Value = for
Key = 40, Value = Welcome
Key = 10, Value = Geeks
Key = 30, Value = Geeks
2.Synchronized HashMap: Java HashMap是一个非同步化的集合类。如果我们需要对它进行线程安全的操作,那么我们必须明确地对它进行同步。java.util.Collections类的synchronizedMap()方法被用来同步化它。它返回一个由指定Map支持的同步(线程安全)Map。
同步的HashMap演示。
// 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<Integer, String> hmap
= new HashMap<Integer, String>();
// 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 HashMap, 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的区别。
并发HashMap | 同步的HashMap |
---|---|
ConcurrentHashMap是一个实现了ConcurrentMap和可序列化接口的类。 | 我们可以通过使用java.util.Collections类的synchronizedMap()方法来同步HashMap。 |
它锁定了Map的某些部分。 | 它锁定了整个Map。 |
ConcurrentHashMap允许执行并发的读和写操作。因此,性能相对来说比同步Map要好。 | 在Synchronized HashMap中,多个线程不能同时访问该Map。因此,其性能相对低于ConcurrentHashMap。 |
ConcuurentHashMap不允许插入null作为一个键或值。 | 同步的HashMap允许插入null作为一个键。 |
ConccurentHashMap不扔ConcurrentModificationException。 | 同步的HashMap抛出ConcurrentModificationException。 |