部分内容待完善...
分析ConcurrentHashMap之前,首先要对Map和HashMap逐个分析,才能更好得理解ConcurrentHashMap。所以这片文章主要来分析HashMap。
1、Map简介
如图Map是一个接口,除此之外常用的集合类接口还有Collection
2、HashMap分析
2.1 源码分析
jdk1.7与1.8关于hashmap做了些许改动,主要就是hash冲突时对数据的处理由1.7中的拉链法变为了1.8中的红黑树(冲突数据大于8)。因为1.8中的源码过于复杂,所以这里只分析几个关键的方法和参数。
初始化容量
/** * The default initial capacity - MUST be a power of two. */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
首先来查看HashMap关于初始化容量的定义,这里容量定义为1<<4,也就是0001(二进制)左移4位变为1000(二进制),也就是16。具体为何这样定义可以参考代码注释,主要是为了提醒初始化容量需定义为2的幂。
负载因子定义
/** * The load factor used when none specified in constructor. */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
这里负载因子定义为0.75,即当前hashmap中实际大小大于16*0.75=12时,就要进行扩容
红黑树转化阈值
/** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */
static final int TREEIFY_THRESHOLD = 8;
上面注释的大概意思是,拉链法中的节点大于8时,将会转换为红黑树。这样就将时间复杂度O(n)变为了O(lgn)
构造函数
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
源码中有好几个重载的构造函数,但主要的还是这个方法。即传入初始化大小和负载因子的方法。这个threshold的主要作用就是用来计算负载的。比如初始化长度为12,那么要在什么情况下扩容呢?就是要找出最接近的2的幂,然后计算。比如找出16,在乘以负载因子0.75
大家可能会注意,最后一行有个tableSizeFor方法,传入了一个初始化长度,下面就详细说下这个方法。这个方法设计非常巧妙,主要就是返回大于当前长度最接近的2的n次幂,比如cap=12,则返回16,主要就是运用了位操作。
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
我举个长度为12的例子
cap的二进制 0000 1100 //十进制为12
n=cap-1即11 0000 1011 //十进制为11
n |= n >>> 1,这个操作是n与n右移一位然后进行或操作
0000 1011
0000 0101
或操作后
0000 1111 此时的n
同理 n |= n >>> 2,这个操作是n与n右移两位然后进行或操作
0000 1111
0000 0011
或操作后
0000 1111
....
最后发现n就是 0000 1111 即十进制的15
经过上边一串位操作后,会发现n结果等于15,然后返回n+1即16。可以发现,上边的一串位操作其实就是把当前位即后边的位都变为1,这样结果就为2的n次幂减1了。
数据插入
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) //如果table为0或空,则进行resize
n = (tab = resize()).length;
//这个是计算下标,取模操作,如果为空,则直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//else的情况有两种
//1、key值一样,则替换value
//2、key不一样,则拉链法,长度过长后转换为红黑树
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//此时e已经被赋值为冲突的节点
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;
}
这里基本上都做了注释,具体可以看注释。
Node节点定义
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); }
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
这是HashMap中节点的定义,它其实是单项链表。
扩容算法实现
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;//当前table容量
int oldThr = threshold; //threshold为当前hashmap负载情况,具体在tableSizeFor函数实现,默认为16*0.75
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//把oldCap(旧表长度左移两位,即扩大两倍)oldCap*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // 同样阈值也要乘2
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//把oldTab中的节点重新rehash到新的tab中去
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//单节点的情况直接进行与操作定位
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//对红黑树进行rehash
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 对链表进行rehash
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
该段代码主要是用来初始化hashmap或是对hashmap扩容,具体请看代码注释