我正在阅读文章“Java理论与实践:构建更好的HashMap”,它对ConcurrentHashMap的实现进行了优秀的概述。
我在Stackoverflow上也发现了一些讨论这里。
我心中的疑问是:“ConcurrentHashMap在哪些场景/应用/地方被使用?”
谢谢。
我在Stackoverflow上也发现了一些讨论这里。
我心中的疑问是:“ConcurrentHashMap在哪些场景/应用/地方被使用?”
谢谢。
如果你计划让多个线程使用地图,那么在与使用HashMap
相同的情况下,你将使用ConcurrentHashMap
。
对于大型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
时尝试更改Map中的值,就会出现ConcurrentModificationException
异常!(具体来说,在执行语句:String key = itr1.next();
时会抛出异常)
我将其用于多线程服务器中从用户ID到用户对象的快速查找。
我有一个网络线程、一个定时器线程用于周期性任务和一个处理控制台输入的线程。多个线程访问用户的哈希映射,因此它需要是线程安全的。