文章目录
HashMap线程不安全的原因
Hashtable在一些方法中加入了synchronized关键字来实现线程安全</br>
区别:[1]
- Hashtable允许同步(synchronized),是
线程安全
的,而HashMap不是线程安全的,因为非同步(unsynchronized)的对象比同步的对象性能表现更好,当不需要考虑线程安全问题时,用Hashtable效率更高
</br> - HashMap允许有
一个key值为null
,并且允许(任意多的)values值为null
而Hashtable不允许key为null,也不允许values为null
</br>
JDK8源码理解:
node节点的数量默认为16
(= 1 << 4)
</br>
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
</br>
当hash 值相同的 key 数量小于等于指定值(默认是8),HashMap使用开链法(数组+链表)解决冲突:
</br>
static final int TREEIFY_THRESHOLD = 8;
<font color = red>PS:代码较长可以不看,看后面的总结容易理解</font>
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
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;
}
}
在JDK8中,当hash 值相同的 key 数量大于指定值(默认是8)时使用平衡二叉树来代替链表。
(目的是发生冲突时将get()方法的性能从O(n)提高到O(logn),下面的代码不包含二叉树部分)
HashMap线程不安全的原因
HashMap 在并发执行 put 操作时会引起死循环,导致 CPU 利用率接近100%。因为多线程会导致 HashMap 的 Node 链表形成环形数据结构,一旦形成环形数据结构,Node 的 next 节点永远不为空,就会在获取 Node 时产生死循环 ------《Java并发编程的艺术》
</br>
上面造成死循环是对于JDK7来说的,具体死循环的原因:看这里,其实也不复杂,就是可能产生一个节点数为2的循环链表。
</br>
那在JDK8中,多线程会对HashMap造成什么影响呢?
JDK8源码:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
// 下面的(n-1)&hash相当于hash % n,注意这只有在n为2的幂时才可以这样做,位运算效率更高
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;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
当key不存在时需要增加一个节点:
对应这种情况:
// 下面的(n-1)&hash相当于hash % n,注意这只有在n为2的幂时才可以这样做,位运算效率更高
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// Create a regular (non-tree) node
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
之后,在 putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
方法的最后几行,会增加size:
if (++size > threshold)
resize();
相比于JDK7, JDK8在扩容后不需要再对原来的节点进行rehash,而是把原来一个槽i
的链表分到两个槽里面去:i
和i+oldCap
</br>
比如对于有16个槽的HashMap,元素1,17,33开始都在槽i=1中,扩容后,1和33继续待在槽i=1,而17去了槽i=1+16(即0001变成00001和10001的问题),在下面的代码中也验证了这一点:
如果(e.hash & oldCap) == 0为真,则不用改变位置,比如上面的1和33
(1 & 16) == 0以及(33 & 16) == 0都为真
而(17 & 16) == 0则为假,它要去槽1+16的位置
所以在JDK8中,多线程会对HashMap造成什么影响呢?
</br>
还是拿上面的例子,按照下面JDK8源代码的流程(<font color = orange>对代码不熟悉的话可以先往下看代码</font>):
假设现在有2个线程在执行resize()方法,假设线程1执行到next = e.next;
时被中断(next = e.next
已经执行完),这时线程二执行和线程1一样的resize():
(线程2)
线程2执行完后:
此时线程1恢复运行,注意到此时的next是指向17的,而e是指向1的,当执行到
while ((e = next) != null);
时,e被赋值为17的引用(即指向17),继续循环,do {next = e.next...}while(...);
,而这时17的next是null,不是最开始预想的33,然后e = next之后,e为null,跳出循环所以经线程1处理之后结果为:33被丢掉了,所以在JDK8中可能会
造成原来数据节点的丢失
,因此HashMap不能用于多线程(本来设置HashMap的目的就是用于单线程
)
// 将原来的map拷贝进扩容后的map
if (oldTab != null) {
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 { // preserve order
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;
}
// 原来的位置+oldCap
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;
}
// 原来的位置+oldCap
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
resize方法部分代码:
......
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
......
if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
threshold = newThr;
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
......
// 将原来的map拷贝进扩容后的map
if (oldTab != null) {
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 { // preserve order
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;
}
// 原来的位置+oldCap
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;
}
// 原来的位置+oldCap
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
Hashtable在一些方法中加入了synchronized关键字来实现线程安全
比如:
public synchronized boolean containsKey(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
}
}
return false;
}
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
但是众所周知,加入synchronized后,所有线程会竞争一把锁,导致程序的运行效率降低。
<font color = red>为了兼顾效率和多线程,我们可以使用ConcurrentHashMap</font>
另外synchronizedMap类也可以实现多线程安全,但是效率不如ConcurrentHashMap.
(synchronizedMap也是使用关键字synchronized,但是它不像Hashtable那样,用synchronized括住整个方法,它是在方法体里面使用synchronized锁住代码块)
详细参考:这里