hashmap:线程不安全
hashtable:通过synchronized保证线程安全但效率低。强一致性
ConcurrentHashMap:弱一致性
数据结构
ConcurrentHashMap为node数组+链表+红黑树。约等于hashmap
//第一次使用时初始化,大小2^n
transient volatile Node<K,V>[] table;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;//不允许value改变值,避免加锁
volatile Node<K,V> next;//不能改变next,只能头插
}
key和value不能为null:
hashmap可以为null,通过containsKey()处理歧义,区别值为null还是值不存在
ConcurrentHashMap是并发的,get和containsKey并不是原子操作,所以无法区别歧义
锁
JDK1.8 中采用CAS + synchronized,锁首节点,粒度更小
// jdk1.7分段segment加锁,跨段操作时,按顺序锁定全部段,按顺序解锁。
//继承ReentrantLock加锁解锁,保证每个 Segment 是线程安全
static class Segment<K,