ArrayBlockingQueue和LinkedBlockingQueue區(qū)別
- 都實現(xiàn)BlockingQueue接口
- 都是阻塞隊列本冲,通過ReetrantLock和Condition實現(xiàn)同步,Condition的await()和signal()實現(xiàn)線程通信
- LinkedBlockingQueue內(nèi)部兩把鎖升酣,讀鎖takeLock和寫鎖putLock
- ArrayBlockingQueue內(nèi)部讀寫使用一把鎖诫睬,可分為公平鎖非公平鎖
/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();
/** Wait queue for waiting takes */
private final Condition notEmpty = takeLock.newCondition();
/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();
/** Wait queue for waiting puts */
private final Condition notFull = putLock.newCondition();
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
- LinkedBlockingQueue通過鏈表實現(xiàn)煞茫,ArrayBlockingQueue通過數(shù)組實現(xiàn)
- LinkedBlockingQueue clear()方法使用兩把鎖
HashMap
-
hash異或移位運算作用
擾動函數(shù),使key均勻分布
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
-
數(shù)組長度是2的n次冪
- 計算hash時,由&代替%续徽,提高效率
- 擴容
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
從圖中可知蚓曼,(n-1)&hash來確定tab索引,2的n次冪-1轉(zhuǎn)成二進制最高位是0其余全為1钦扭,與key的hash值做&運算纫版,結(jié)果是key的低位保持不變,即平均分在各個數(shù)組里面客情。
注:兩數(shù)&其弊,都是1為1,否則為0
- 1.8之后鏈表長度>=8并且數(shù)組長度>=64膀斋,才轉(zhuǎn)為紅黑樹梭伐,否則只進行擴容
- 擴容:1.7 擴容使用的是頭插法,會造成死循環(huán)
1.8 使用尾插法仰担,擴容之后元素要么在原位置糊识,要么在原位置+原數(shù)組長度,通過倒數(shù)第5位即可確定摔蓝。
- 數(shù)組長度計算:如果初始化傳入的長度不是2的n次冪赂苗,hashmap會轉(zhuǎn)成比他大的最近的2的n次冪。
ConcurrentHashMap
- 通過CAS+synchronized實現(xiàn)線程安全