new ConcurrentHashMap()传入
默认值
:
容量:initialCapacity —> 16
负载因子:loadFactor —> 0.75
并发级别:concurrencyLevel —> 16
public ConcurrentHashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
}
新建segment0 入参为:
负载因子0.75
阈值大小1
hashEntry数组
public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
// 首先判断传入的参数是否大于0,如果是则抛出异常;
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
// concurrencyLevel最大值为segment的最大段数MAX_SEGMENTS( 1 << 16 )
if (concurrencyLevel > MAX_SEGMENTS)
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
int sshift = 0;
int ssize = 1;
// 然后赋予两个值segment段数ssize = 16,sshift = 4(相当于是2的幂次方)
while (ssize < concurrencyLevel) {
++sshift;
ssize <<= 1;
}
// segmentShift = 18(利用右移得到高四位,用于put时获取segment的下标)
this.segmentShift = 32 - sshift;
// segmentMask = 15(和segmentShift 合作,进行与运算得到segment的下标)
this.segmentMask = ssize - 1;
// initialCapacity最大值为MAXIMUM_CAPACITY最大容量(1 << 30 )
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
// c ---> 16/15 +1 ---> 2
int c = initialCapacity / ssize;
if (c * ssize < initialCapacity)
++c;
int cap = MIN_SEGMENT_TABLE_CAPACITY;
// 将c和cap进行大小判断,cap最小值为MIN_SEGMENT_TABLE_CAPACITY = 2,循环判断如果cap比c小则左移一位
while (cap < c)
cap <<= 1;
// create segments and segments[0]
// 创建segment数组和segment[0],后续put的值会根据segment[0]的长度、阈值、负载因子创建新的segment
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];
// 新建segment数组,将segment0添加进数组
UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
this.segments = ss;
}
segment的put()方法
concurrentHashMap的put()方法中,是不允许key和value为null值的,至于为什么,在网上看到的一句话为:
ConcurrentHashMap不能put null 是因为 无法分辨是key没找到的null还是有key值为null,这在多线程里面是模糊不清的,所以压根就不让put null。
public V put(K key, V value) {
Segment<K,V> s;
if (value == null)
throw new NullPointerException();
int hash = hash(key);
int j = (hash >>> segmentShift) & segmentMask;
if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
(segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
s = ensureSegment(j);
return s.put(key, hash, value, false);
}
hash(key)经过移位和异或得到hash,目的是为了让hash值更加混乱,得到的segment下标更加分散
private int hash(Object k) {
int h = hashSeed;
if ((0 != h) && (k instanceof String)) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
将hash无符号右移位18位,将hash的高4位和segmentMask(15:1111)进行与运算得到segment数组的下标
int j = (hash >>> segmentShift) & segmentMask;
该方法是新建segment数组放到指定的下标中,其中SBASE和SSHIFT是调用UNSAFE的方法:
SBASE = UNSAFE.arrayBaseOffset(sc); // 数组中第一个元素的起始位置
ss = UNSAFE.arrayIndexScale(sc); // 数组中存储的对象的对象头大小
SSHIFT = 31 – Integer.numberOfLeadingZeros(ss); // Integer.numberOfLeadingZeros获得ss中高位0的个数
if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
(segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
s = ensureSegment(j);
ensureSegment()
ensureSegment()方法中根据segment[0]初始化的阈值、长度、负载因子创建new Segment对象,然后根据UNSAFE的两个属性得到下标,通过CAS的方式添加进Segment数组当中
private Segment<K,V> ensureSegment(int k) {
final Segment<K,V>[] ss = this.segments;
long u = (k << SSHIFT) + SBASE; // raw offset
Segment<K,V> seg;
if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
Segment<K,V> proto = ss[0]; // use segment 0 as prototype
int cap = proto.table.length;
float lf = proto.loadFactor;
int threshold = (int)(cap * lf);
HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
== null) { // recheck
Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
== null) {
if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
break;
}
}
}
return seg;
}
HashEntry的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))) {
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);
else
setEntryAt(tab, index, node);
++modCount;
count = c;
oldValue = null;
break;
}
}
} finally {
unlock();
}
return oldValue;
}
进入hashEntry的put方法
tryLock()方法 是**
ReentrantLock
(独占可重入锁)下的方法,使用
CAS修改
**state值,将当前线程为独占线程,如果进来的线程等于当前独占线程,则设置state+1
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
将hahs的低16位和table.length – 1(15:1111)进行**
与运算
**得到hashEntry下标
int index = (tab.length - 1) & hash;
查看存放的位置是否为null:
如果
不为null
则进行添加值或者替换值;
if ((k = e.key) == key ||
(e.hash == hash && key.equals(k))) {
oldValue = e.value;
if (!onlyIfAbsent) {
e.value = value;
++modCount;
}
break;
}
e = e.next;
如果
为null
,则直接添加new HashEntry<K,V>(hash, key, value, first); 使用**
头插法
**
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);
else
setEntryAt(tab, index, node);
++modCount;
count = c;
oldValue = null;
break;
完成put操作之后,在finally中要进行**
unlock()解锁
**,返回值为被修改的oldValue
如果在put操作过程中,容量**
超过阈值
,则进行
扩容操作
,同样是创建一个两倍大的HashEntry,
先扩容后添加
**,这里不再细说
private void rehash(HashEntry<K,V> node) {
HashEntry<K,V>[] oldTable = table;
int oldCapacity = oldTable.length;
int newCapacity = oldCapacity << 1;
threshold = (int)(newCapacity * loadFactor);
HashEntry<K,V>[] newTable =
(HashEntry<K,V>[]) new HashEntry[newCapacity];
int sizeMask = newCapacity - 1;
for (int i = 0; i < oldCapacity ; i++) {
HashEntry<K,V> e = oldTable[i];
if (e != null) {
HashEntry<K,V> next = e.next;
int idx = e.hash & sizeMask;
if (next == null) // Single node on list
newTable[idx] = e;
else { // Reuse consecutive sequence at same slot
HashEntry<K,V> lastRun = e;
int lastIdx = idx;
for (HashEntry<K,V> last = next;
last != null;
last = last.next) {
int k = last.hash & sizeMask;
if (k != lastIdx) {
lastIdx = k;
lastRun = last;
}
}
newTable[lastIdx] = lastRun;
// Clone remaining nodes
for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
V v = p.value;
int h = p.hash;
int k = h & sizeMask;
HashEntry<K,V> n = newTable[k];
newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
}
}
}
}
int nodeIndex = node.hash & sizeMask; // add the new node
node.setNext(newTable[nodeIndex]);
newTable[nodeIndex] = node;
table = newTable;
}