ConcurrentHashMap简介:
ConcurrentHashMap是线程安全且高效的HashMap,使用锁分段技术提高并发访问率;
ConcurrentHashMap的结构:
ConcurrentHashMap的结构ConcurrentHashMap包含一个Segment[]数组,每个Segment包含一个HashEntry[]数组,数组中每个元素是由HashEntry组成的链表;
ConcurrentHashMap的初始化:
先根据concurrencyLevel计算出segment数组的大小,再结合initialCapacity计算出segment里HashEntry数组的大小,最后初始化segment、初始化segment数组;
//concurrencyLevel表示并发级别,默认值为16;initialCapacity表示ConcurrentHashMap的容量
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (concurrencyLevel > MAX_SEGMENTS)
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
int sshift = 0;
//ssize是segment数组的长度
int ssize = 1;
//ssize通过concurrencyLevel计算得出,是大于等于concurrencyLevel的最小2的N次方值
while (ssize < concurrencyLevel) {
++sshift;
ssize <<= 1;
}
this.segmentShift = 32 - sshift;
this.segmentMask = ssize - 1;
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
int c = initialCapacity / ssize;
if (c * ssize < initialCapacity)
++c;
//cap是segment里HashEntry数组的长度
int cap = MIN_SEGMENT_TABLE_CAPACITY;
//cap是满足cap*ssize>=initialCapacity条件的最小2的N次方值
while (cap < c)
cap <<= 1;
//segment的容量threshold=cap * loadFactor
Segment<K,V> s0 =
new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
(HashEntry<K,V>[])new HashEntry[cap]);
Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
this.segments = ss;
}
segmentShift和segmentMask:
segmentShift用于定位参与散列运算的位数,segmentShift=32-sshift;
segmentMask是散列运算的掩码,segmentShift=ssize-1;
注:ssize=2^sshift
网友评论