1.7 构造函数
// 16 0.75 16
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (concurrencyLevel > MAX_SEGMENTS) //1 << 16 65536
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
//找到最接近的2的幂次方数
int sshift = 0;
int ssize = 1;//segment数组的长度
while (ssize < concurrencyLevel) {
++sshift; // 1 2 3 [4] 5 取hash的高四位,put时候用高4(sshift)位求segment数组的index值,低4位用于求hashtable[]的index值
ssize <<= 1;//左移 2 4 8 [16] 32
}
this.segmentShift = 32 - sshift; //28
this.segmentMask = ssize - 1;// 16 -1(0000 1111) 用来取table index = hash & (ssize -1)
if (initialCapacity > MAXIMUM_CAPACITY)//1 << 30 1073741824
initialCapacity = MAXIMUM_CAPACITY;
int c = initialCapacity / ssize; // 16/16 = 1 每个segment里面的hashEntry数组的数量
if (c * ssize < initialCapacity) //initialCapacity=16 初始参数 保证总hashEntry数量大于初始化得数量
++c;
int cap = MIN_SEGMENT_TABLE_CAPACITY; // MIN_SEGMENT_TABLE_CAPACITY = 2
while (cap < c)
cap <<= 1;//左移 2的幂次数 hashEntry[]数组的长度也要是2的幂次方
// create segments and segments[0]
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]//Unsafe CAS技术
this.segments = ss;
}
1.7 ConcurrentHashmap.put()
@SuppressWarnings("unchecked")
public V put(K key, V value) {
Segment<K,V> s;
if (value == null)
throw new NullPointerException();
int hash = hash(key);
//segmentShift默认值是32 -4 =28,int值一共32位 所以取hash值的高四位
int j = (hash >>> segmentShift) & segmentMask;//使用hash值的高4位 &segmentMask是segment长度减1
if ((s = (Segment<K,V>)UNSAFE.getObject // Unsafe检查segment时候存在
(segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
s = ensureSegment(j); //新建并使用CAS插入segment
return s.put(key, hash, value, false);//将键值对插入Segment
}
Segment.put()
Segment.put
final V put(K key, int hash, V value, boolean onlyIfAbsent) {
HashEntry<K,V> node = tryLock() ? null :
scanAndLockForPut(key, hash, value);
V oldValue;
try {
HashEntry<K,V>[] tab = table;
int index = (tab.length - 1) & hash;
HashEntry<K,V> first = entryAt(tab, index);//获取第一个节点
for (HashEntry<K,V> e = first;;) {//遍历链表
if (e != null) {
K k;
if ((k = e.key) == key ||
(e.hash == hash && key.equals(k))) {//找到key相等的HashEntry 并替换value值
oldValue = e.value;
if (!onlyIfAbsent) {
e.value = value;
++modCount;
}
break;
}
e = e.next;
}
//到达最后一个节点
else {
if (node != null)
node.setNext(first);
else
node = new HashEntry<K,V>(hash, key, value, first);//创建新节点
int c = count + 1;
if (c > threshold && tab.length < MAXIMUM_CAPACITY)
rehash(node);//扩容这个Segment的hashEntry[]数组
else
setEntryAt(tab, index, node);
++modCount;
count = c;
oldValue = null;
break;
}
}
} finally {
unlock();
}
return oldValue;
}
本文详细解析了Java中ConcurrentHashMap的构造函数及put方法实现原理。通过源码分析,阐述了并发级别、负载因子、段大小等参数的设置与影响,以及如何通过散列函数和CAS操作保证线程安全。
1011

被折叠的 条评论
为什么被折叠?



