【发布时间】:2011-05-04 01:41:51
【问题描述】:
我正在阅读文章“Java theory and practice: Building a better HashMap”,它很好地概述了 ConcurrentHashMap 的实现。
我还在 Stackoverflow here 上找到了一些关于它的讨论。
我的疑问是“使用 ConcurrentHashMap 的场景/应用程序/地点是什么”。
谢谢
【问题讨论】:
我正在阅读文章“Java theory and practice: Building a better HashMap”,它很好地概述了 ConcurrentHashMap 的实现。
我还在 Stackoverflow here 上找到了一些关于它的讨论。
我的疑问是“使用 ConcurrentHashMap 的场景/应用程序/地点是什么”。
谢谢
【问题讨论】:
您将在使用HashMap 的相同实例中使用ConcurrentHashMap,但您计划使用映射的线程不止一个。
【讨论】:
例如,我用它来快速查找从用户 ID 到多线程服务器中的用户对象。
我有一个网络线程、一个用于定期任务的计时器线程和一个用于处理控制台输入的线程。多线程访问用户的hash map,需要线程安全。
【讨论】:
对于大型 Map 或大量读写操作,建议使用 ConcurrentHashMap,原因如下:
考虑以下示例:
public class ConcurrentHashMapExample {
public static void main(String[] args) {
//ConcurrentHashMap
Map<String,String> myMap = new ConcurrentHashMap<String,String>();
myMap.put("1", "1");
myMap.put("2", "1");
myMap.put("3", "1");
myMap.put("4", "1");
myMap.put("5", "1");
myMap.put("6", "1");
System.out.println("ConcurrentHashMap before iterator: "+myMap);
Iterator<String> itr1 = myMap.keySet().iterator();
while(itr1.hasNext()){
String key = itr1.next();
if(key.equals("3")) myMap.put(key+"new", "new3");
}
System.out.println("ConcurrentHashMap after iterator: "+myMap);
//HashMap
myMap = new HashMap<String,String>();
myMap.put("1", "1");
myMap.put("2", "1");
myMap.put("3", "1");
myMap.put("4", "1");
myMap.put("5", "1");
myMap.put("6", "1");
System.out.println("HashMap before iterator: "+myMap);
Iterator<String> itr2 = myMap.keySet().iterator();
while(itr2.hasNext()){
String key = itr2.next();
if(key.equals("3")) myMap.put(key+"new", "new3");
}
System.out.println("HashMap after iterator: "+myMap);
}
}
输出将是:
ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1}
HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at com.test.ConcurrentHashMapExample.main(ConcurrentHashMapExample.java:44)
如您所见,对于HashMap,ConcurrentModificationException 将被抛出,因为您尝试更改当前迭代的地图! (具体会在语句上抛出异常:String key = itr1.next();)
【讨论】: