首页 > 其他 > 详细

集合-ConcurrentHashMap-jdk1.7

时间:2020-02-29 22:57:04      阅读:66      评论:0      收藏:0      [点我收藏+]

构造器

@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;
}

  

集合-ConcurrentHashMap-jdk1.7

原文:https://www.cnblogs.com/BINGJJFLY/p/12386523.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!