HashMap非线程并发安全,Hashtable线程并发安全的。
查看Hashtable源码,发现它的读取、添加等方法都添加了同步锁,效率太低。
Hashtable中,会锁住整个表,查询的时候也锁住整个表,效率很低。
那么如何提高效率?
如果只锁操作的一个元素,并发效率会特别高,但是实现太难。
解决思想:引入分段锁(分段桶)
ConcurrentMap
是通过其内部的算法,将这个表划分为16个区域(jdk1.7及以下版本),这样操作数据的时候就不会锁住整个表,只会锁其中一个区域,剩下15个区域中的数据不受影响。当然如果要操作的2个数据都在同一个区域的话,那么还是不能同时操作的。
具体的方法和map一样。
public void testConcurrentMap (){
ConcurrentMap<Integer,String> cmap =
new ConcurrentHashMap<Integer,String>();
cmap.put(1, "一");
cmap.put(2,"二");
cmap.put(3,"三");
System.out.println();
并发导航映射ConcurrentNavigableMap
根据指定的key获取符合条件的子map,headMap()、tailMap()、subMap()
1.headMap(K toKey):获取小于toKey的所有键值对
2.subMap(K fromKey,K toKey):获取小于等于fromKey,小于toKey的所有键值对
3.tailMap(K fromKey):获取>=fromKey所有的键值对
以上方法获取后,源集合中的内容不变。相当于获取的副本。
public void testConcurrentNavigableMap(){
ConcurrentNavigableMap<Integer,String> cmap=
new ConcurrentSkipListMap<Integer,String>();
cmap.put(1, "一");
cmap.put(2,"二");
cmap.put(3,"三");
cmap.put(4,"四");
cmap.put(5,"五");
cmap.put(6,"六");
ConcurrentNavigableMap<Integer,String> headMap=
cmap.headMap(2);
printMap(headMap);
System.out.println("------------");
ConcurrentNavigableMap<Integer,String> subMap=
cmap.subMap(3, 4);
printMap(subMap);
System.out.println("------------");
printMap(cmap.tailMap(5));
System.out.println("------------");
printMap(cmap);
}
private void printMap(Map<Integer,String> map){
for (Map.Entry<Integer,String> entry : map.entrySet()) {
System.out.println(entry.getKey()+"="+entry.getValue());
}
}