ConcurrentHashMap 的结构分析
那么mm就有点疑问了,ConcurrentHashMap是如何定位到一个元素的??????
ConcurrentHashMap定位一个元素的过程需要进行两次的hash操作,第一次Hash定位Segment,第二次hash定位到元素所在的链表头部
这会造成hash的过程要比hashmap要长,但是带来的好处是写操作的时候可以只对元素所在的segment进行加锁即可,不会影响其他的segment,
这样ConcurrentHashMap可以最高同时支持Segment数量大小的写操作
然后大大提高了ConcurrentHashMap的读写性能
然后它的微妙之处,且等慢慢道来
ConcurrentHashMap数据结构
// 散列映射表的默认初始容量为16 ,即初始默认为16个桶
static final int DEFAULT_INITIAL_CAPACITY = 16;
//装载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//散列表默认的并发级别为16 即默认有16个segment
static final int DEFAULT_CONCURRENCY_LEVEL = 16;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
static final int RETRIES_BEFORE_LOCK = 2;
//egments 的掩码值
final int segmentMask;
//偏移量
final int segmentShift;
//由 Segment 对象组成的数组
final Segment<K, V>[] segments;//segments是final类型的,说明concurrentHashMap的扩容是不增加segmengts的长度的,只是在单个段里做扩容
Set<K> keySet;
Set<Map.Entry<K, V>> entrySet;
Collection<V> values;
Segment的数据结构
static final class Segment<K, V> extends ReentrantLock {
private static final long serialVersionUID = 5207829234977119743L;
transient volatile int count;//segment中元素的数量,可见的