集合-ConcurrentHashMap-jdk1.7

构造器

@SuppressWarnings("unchecked")
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;
	// Segment数组容量
	int ssize = 1;
	// 保证Segment数组容量是2的幂次方
	while (ssize < concurrencyLevel) {
		++sshift;
		ssize <<= 1;
	}
	this.segmentShift = 32 - sshift;
	// Segment数组容量是不变的,可以预计算求数组地址索引公式的参数值,hash & ( length - 1 ) -> hash & segmentMask
	this.segmentMask = ssize - 1;
	if (initialCapacity > MAXIMUM_CAPACITY)
		initialCapacity = MAXIMUM_CAPACITY;
	// 计算Segment内的HashEntry数组的容量
	int c = initialCapacity / ssize;
	// 向上取值如initialCapacity / ssize为1.9,此时c为1,那么要容量要进1得2
	if (c * ssize < initialCapacity)
		++c;
	// Segment内的HashEntry数组的容量
	int cap = MIN_SEGMENT_TABLE_CAPACITY;
	// 保证Segment内的HashEntry数组的容量是2的幂次方
	while (cap < c)
		cap <<= 1;
	// create segments and segments[0]
	// 初始化Segment数组中的第一元素值,一个Segment类似于一个HashMap
	Segment<K,V> s0 =
		new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
						 (HashEntry<K,V>[])new HashEntry[cap]);
	// 初始化Segment数组
	Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
	// 原子操作为Segment数组的第一个元素赋值
	UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
	this.segments = ss;
}

  

posted @ 2020-02-29 22:08  BINGJJFLY  阅读(226)  评论(0编辑  收藏  举报