concurrentHashMap爲了保證線程安全採用了段鎖的機制(jdk1.7):
concurrentHashMap內部構造了一個Segment段鎖內部類,它繼承自ReentrantLock部分如下
static final class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
static final int MAX_SCAN_RETRIES =
Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
transient volatile HashEntry<K,V>[] table;
transient int count;
transient int modCount;
transient int threshold;
final float loadFactor;
Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
this.loadFactor = lf;
this.threshold = threshold;
this.table = tab;
}
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;
}
@SuppressWarnings("unchecked")
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;
}
}
成員變量:
// 默認大小
static final int DEFAULT_INITIAL_CAPACITY = 16;
//初始的加載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//初始的併發等級(下面會敘述作用)
static final int DEFAULT_CONCURRENCY_LEVEL = 16;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//最小的segment數量
static final int MIN_SEGMENT_TABLE_CAPACITY = 2;
//最大的segment數量
static final int MAX_SEGMENTS = 1 << 16;
構造方法:
//通過指定的容量,加載因子和併發等級創建一個新的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;
// 下面即通過併發等級來確定Segment的大小
//sshift用來記錄向左按位移動的次數
int sshift = 0;
//ssize用來記錄Segment數組的大小
int ssize = 1;
//Segment的大小爲大於等於concurrencyLevel的第一個2的n次方的數
while (ssize < concurrencyLevel) {
++sshift;
ssize <<= 1;
}
this.segmentShift = 32 - sshift;
//segmentMask的值等於ssize - 1(這個值很重要)
this.segmentMask = ssize - 1;
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//c記錄每個Segment上要放置多少個元素
int c = initialCapacity / ssize;
//假如有餘數,則每個Segment放置元素加1
if (c * ssize < initialCapacity)
++c;
int cap = MIN_SEGMENT_TABLE_CAPACITY;
while (cap < c)
cap <<= 1;
//創建第一個Segment,並放入Segment[]數組中,作爲第一個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];
UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
this.segments = ss;
}
插入操作
public V put(K key, V value) {
Segment<K,V> s;
//ConcurrentHashMap的key和value都不能爲null
if (value == null)
throw new NullPointerException();
//這裏對key求hash值,並確定應該放到segment數組的索引位置
int hash = hash(key);
//j爲索引位置,思路和HashMap的思路一樣,這裏不再多說
int j = (hash >>> segmentShift) & segmentMask;
if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
(segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
s = ensureSegment(j);
//這裏很關鍵,找到了對應的Segment,則把元素放到Segment中去
return s.put(key, hash, value, false);
}
找到對應的段鎖之後進入加鎖 中間和HashMap類似 釋放鎖
final V put(K key, int hash, V value, boolean onlyIfAbsent) {
//這裏是併發的關鍵,每一個Segment進行put時,都會加鎖
HashEntry<K,V> node = tryLock() ? null :
scanAndLockForPut(key, hash, value);
V oldValue;
try {
//tab是當前segment所連接的HashEntry數組
HashEntry<K,V>[] tab = table;
//確定key的hash值所在HashEntry數組的索引位置
int index = (tab.length - 1) & hash;
//取得要放入的HashEntry鏈的鏈頭
HashEntry<K,V> first = entryAt(tab, index);
//遍歷當前HashEntry鏈
for (HashEntry<K,V> e = first;;) {
//如果鏈頭不爲null
if (e != null) {
K k;
//如果在該鏈中找到相同的key,則用新值替換舊值,並退出循環
if ((k = e.key) == key ||
(e.hash == hash && key.equals(k))) {
oldValue = e.value;
if (!onlyIfAbsent) {
e.value = value;
++modCount;
}
break;
}
//如果沒有和key相同的,一直遍歷到鏈尾,鏈尾的next爲null,進入到else
e = e.next;
}
else {//如果沒有找到key相同的,則把當前Entry插入到鏈頭
if (node != null)
node.setNext(first);
else
node = new HashEntry<K,V>(hash, key, value, first);
//此時數量+1
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;
}
Java基礎總結 - ConcurrentHashMap詳解
Java基礎總結 - ConcurrentHashMap詳解
這篇文章只是把大學記的筆記整理到博客,方便自己查看,不保證權威性(•̀ᴗ•́)و ̑̑
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.