hashMap是非线程安全的,表现在两种情况下:

  1 扩容:

    t1线程对map进行扩容,此时t2线程来读取数据,原本要读取位置为2的元素,扩容后此元素位置未必是2,则出现读取错误数据。

  2 hash碰撞

    两个线程添加元素发生hash碰撞,都要将此元素添加到链表的头部,则会发生数据被覆盖。

 详情:

HashMap底层是一个Node数组,一旦发生Hash冲突的的时候,HashMap采用拉链法解决碰撞冲突,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;
}
}

Node的变量:

final int hash;
final K key;
V value;
Node<K,V> next;
执行put方法添加元素后调用此方法:
/**
* 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;
if ((p = tab[i = (n - 1) & hash]) == null)
//1位置 此位置为空,则直接创建newNode
tab[i] = newNode(hash, key, value, null);
else {
//如果此处有元素
Node<K,V> e; K k;
//如果此处有元素,且key值相同,则覆盖元素
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);
//剩余情况,将新元素追加到当前链表元素的next节点
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果链表长度达到8,要将链表结构转化为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果发现相同的key,同样覆盖
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;
}

在并发情况下,添加元素,在 1位置 会出现线程安全问题

扩容问题:

    /**
* 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;
//旧map长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//要调整大小的下一个值
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//如果当前数组长度大于等于最大值(1 << 30),就把threshold调到最大,无法再创建更大的数组了,直接返回原有数据
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果当前长度*2 小于最大值,并且当前长度大于等于默认长度16,阈值*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//如果阈值大于0,则将新数组的长度设置为阈值=16
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) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
//为每个不为空的key重新计算hash值
newTab[e.hash & (newCap - 1)] = e;
//处理红黑树中数据
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//处理链表数据
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;
}
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;
}

线程1在取数据时,map被其它线程扩容,则造成取到错误数据

hashMap的线程不安全的更多相关文章

  1. HashMap为什么线程不安全(hash碰撞与扩容导致)

    一直以来都知道HashMap是线程不安全的,但是到底为什么线程不安全,在多线程操作情况下什么时候线程不安全? 让我们先来了解一下HashMap的底层存储结构,HashMap底层是一个Entry数组,一 ...

  2. 为什么说 HashMap 是非线程安全的?

    我们在学习 HashMap 的时候,都知道 HashMap 是非线程安全的,同时我们知道 HashTable 是线程安全的,因为里面的方法使用了 synchronized 进行同步. 但是 HashM ...

  3. Java基础知识强化之集合框架笔记80:HashMap的线程不安全性的体现

    1. HashMap 的线程不安全性的体现: 主要是下面两方面: (1)多线程环境下,多个线程同时resize()时候,容易产生死锁现象.即:resize死循环 (2)如果在使用迭代器的过程中有其他线 ...

  4. HashMap变成线程安全方法

    我们都知道.HashMap是非线程安全的(非同步的).那么怎么才能让HashMap变成线程安全的呢? 我认为主要可以通过以下三种方法来实现: 1.替换成Hashtable,Hashtable通过对整个 ...

  5. Java并发基础08. 造成HashMap非线程安全的原因

    在前面我的一篇总结(6. 线程范围内共享数据)文章中提到,为了数据能在线程范围内使用,我用了 HashMap 来存储不同线程中的数据,key 为当前线程,value 为当前线程中的数据.我取的时候根据 ...

  6. 面试官:小伙子,你给我说一下HashMap 为什么线程不安全?

    前言:我们都知道HashMap是线程不安全的,在多线程环境中不建议使用,但是其线程不安全主要体现在什么地方呢,本文将对该问题进行解密. 1.jdk1.7中的HashMap 在jdk1.8中对HashM ...

  7. HashMap 为什么线程不安全?

    作者:developer http://cnblogs.com/developer_chan/p/10450908.html 我们都知道HashMap是线程不安全的,在多线程环境中不建议使用,但是其线 ...

  8. 验证hashmap非线程安全

    http://www.blogjava.net/lukangping/articles/331089.html final HashMap<String, String> firstHas ...

  9. HashMap非线程安全分析

    通过各方资料了解,HashMap不是线程安全的,但是为什么不是线程安全的,在什么情况下会出现问题呢? 1. 下面对HashMap做一个实验,两个线程,并发写入不同的值,key和value相同,最后再看 ...

随机推荐

  1. Java Transaction Management

    Just a few weeks ago, I had a discussion with one of my colleagues about how to manage the transacti ...

  2. Shell脚本之:if-else

    Shell 有三种 if ... else 语句: 1.if ... fi 语句: 2.if ... else ... fi 语句: 3.if ... elif ... else ... fi 语句. ...

  3. dom控制

    (1)创建新节点 createDocumentFragment()    //创建一个DOM片段 createElement_x_x()   //创建一个具体的元素 createTextNode()  ...

  4. pom.xml基础配置

    pom.xml基础配置: maven中,最让我迷惑的还是那一堆配置! 就拿这个属性配置来说: 我需要让整个项目统一字符集编码,就需要设定 <project.build.sourceEncodin ...

  5. 【转载】关于 .Net 逆向的那些工具:反编译篇

    在项目开发过程中,估计也有人和我遇到过同样的经历:生产环境出现了重大Bug亟需解决,而偏偏就在这时仓库中的代码却不是最新的.在这种情况下,我们不能直接在当前的代码中修改这个Bug然后发布,这会导致更严 ...

  6. HDU 3416

    Marriage Match IV Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  7. python thrift hbase安装连接

    默认已装好 hbase,我的版本是hbase-0.98.24,并运行 python 2.7.x 步骤: sudo apt-get install automake bison flex g++ git ...

  8. HDU 2242 考研路茫茫——空调教室(边双连通)

    HDU 2242 考研路茫茫--空调教室 题目链接 思路:求边双连通分量.然后进行缩点,点权为双连通分支的点权之和,缩点完变成一棵树,然后在树上dfs一遍就能得出答案 代码: #include < ...

  9. linux配置nfs步骤及心得

      这节我们介绍NFS的相关概念,以及怎样配置NFS和在client中查看NFS.   NFS的配置过程非常easy. 在server端中编辑/etc/exports文件,加入例如以下内容:      ...

  10. 加入 centos 右键 terminal

    centos6.2以上默认右键都没有terminal,现加入方法 例如以下 1>  yum -y install nautilus-open-terminal 2> shutdown -r ...