1.HashMap和CurrentHashMap在1.8中的两者的源码基本一致,但是后者使用了cas操作,有些地方加上了锁;
2.hashTable中的锁是通过锁put方法实现的,即使不同的线程put不同下标的元素都被上了锁。但是实际上,只有在多个线程对同一个下标的位置进行put操作时才是多线程安全问题的根本原因(可以用CAS操作)。
3.CurrentHashMap完成的工作就是希望能在不同的链表上不上锁,在相同的链表上上锁,比较容易的就是我们对表进行上锁;
4.源码核心的put方法:可以极大程度的提升效率,原因在于hash算法本身就是散列算法,这样大部分的put操作就不会再hash的table的某个位置聚集,这时就是CurrentHashMap的put方法只针对:1.hash的table数组的表头使用cas操作,多线程同时访问时,自旋实现。2.对某个指定位置的list列表使用put方法保证多个线程不会同时修改元素;极大的提升了效率。
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());//计算hash值
int binCount = 0;
for (Node<K,V>[] tab = table;;) {//将实际的table赋值给tab
Node<K,V> f; int n, i, fh;//定义首节点,长度,等
if (tab == null || (n = tab.length) == 0)
tab = initTable();//表为空就初始化一个表
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {//给f赋值,将其中搞得元素赋值给f,就是表头
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))//**当多个线程对表头进行操作时使用了cas操作,一种补偿机制;保证了数组某个下标位置只能有一个线程添加成功;**
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {//此处是对表头上锁,保证链表不会被多线程所修改;
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
5.cas的以及锁的操作位置: