ArrayBlockingQueue和LinkedBlockingQueue区别
- 都实现BlockingQueue接口
- 都是阻塞队列,通过ReetrantLock和Condition实现同步,Condition的await()和signal()实现线程通信
- LinkedBlockingQueue内部两把锁,读锁takeLock和写锁putLock
- ArrayBlockingQueue内部读写使用一把锁,可分为公平锁非公平锁
/** 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通过链表实现,ArrayBlockingQueue通过数组实现
- LinkedBlockingQueue clear()方法使用两把锁
HashMap
-
hash异或移位运算作用
扰动函数,使key均匀分布
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
-
数组长度是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转成二进制最高位是0其余全为1,与key的hash值做&运算,结果是key的低位保持不变,即平均分在各个数组里面。
注:两数&,都是1为1,否则为0
- 1.8之后链表长度>=8并且数组长度>=64,才转为红黑树,否则只进行扩容
- 扩容:1.7 扩容使用的是头插法,会造成死循环
1.8 使用尾插法,扩容之后元素要么在原位置,要么在原位置+原数组长度,通过倒数第5位即可确定。
- 数组长度计算:如果初始化传入的长度不是2的n次幂,hashmap会转成比他大的最近的2的n次幂。
ConcurrentHashMap
- 通过CAS+synchronized实现线程安全