基本使用
public static void main(String[] args) {
ConcurrentHashMap<String, String> cHashMap = new ConcurrentHashMap<String, String>();
cHashMap.put("cn", "中国");
cHashMap.put("jp", "日本");
cHashMap.put("fr", "法国");
cHashMap.put("cn", "中国2号");
// cHashMap.put(null,"fds");//报null
// cHashMap.put("df",null);//报 null
System.out.println(cHashMap);
System.out.println(cHashMap.toString());
System.out.println("****");
Iterator i = cHashMap.keySet().iterator();
while (i.hasNext()) {
String k = (String) i.next();
String v = cHashMap.get(k);
System.out.println("k:" + k + "v:" + v);
}
}
运行结果
{jp=日本, cn=中国2号, fr=法国}
{jp=日本, cn=中国2号, fr=法国}
****
k:jpv:日本
k:cnv:中国2号
k:frv:法国
总结
- 父类
* @param <V> the type of mapped values
*/
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
private static final long serialVersionUID = 7249069246763182397L;
/*
* Overview:
*
* The primary design goal of this hash table is
- 线程安全
hashMap不是线程安全的,如果多线程使用则需手动自己实现锁 - concurrentHashMap是分段锁
- concurrentHashMap避免了无效扩容(hashMap可能存在无效扩容)
- 锁分段技术
首先将数据分成一段一段的存储,然后给每一段数据配一把锁,当一个线程占用锁访问其中一个段数据的时候,其他段的数据也能被其他线程访问。
ConcurrentHashMap提供了与Hashtable和SynchronizedMap不同的锁机制。Hashtable中采用的锁机制是一次锁住整个hash表,从而在同一时刻只能由一个线程对其进行操作;而ConcurrentHashMap中则是一次锁住一个桶。
ConcurrentHashMap默认将hash表分为16个桶,诸如get、put、remove等常用操作只锁住当前需要用到的桶。这样,原来只能一个线程进入,现在却能同时有16个写线程执行,并发性能的提升是显而易见的
网友评论