我们都知道
HashMap
是线程不安全的,我们应该使用ConcurrentHashMap
。但是为什么HashMap
是线程不安全的呢
先声明:HashMap
的线程不安全体现在会造成**死循环
、数据丢失
、数据覆盖
**这些问题。其中死循环和数据丢失是在JDK1.7中出现的问题,在JDK1.8中已经得到解决,然而1.8中仍会有数据覆盖这样的问题。
HashMap的线程不安全主要是发生在扩容方法中,即根源是在transfer方法中,JDK1.7中HashMap的transfer方法如下:
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
这段代码是HashMap
的扩容操作,重新定位每个桶