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. ThinkPHP示例:CURD

    完整的控制器文件: class IndexAction extends Action { // 查询数据 public function index() { $Form = M("Form& ...

  2. VS2010 C#调用C++ DLL文件 【转】

    http://www.soaspx.com/dotnet/csharp/csharp_20110406_7469.html 背景 在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使用一些第 ...

  3. masm学习

    . .model flat,stdcall option casemap:none ; case sensitive ;http://www.popbook.com/wbbs/topic.asp?l_ ...

  4. 【音乐App】—— Vue-music 项目学习笔记:歌手详情页开发

    前言:以下内容均为学习慕课网高级实战课程的实践爬坑笔记. 项目github地址:https://github.com/66Web/ljq_vue_music,欢迎Star. 歌曲列表 歌曲播放 一.子 ...

  5. 解决使用maven jetty启动后无法加载修改过后的静态资源

    jetty模式是不能修改js文件的,比如你现在调试前端js,发现在myeclipse/eclipse的源码里面无法修改文件,点都不让你点,所以,你只能采用一些办法,更改jetty的模式配置. Look ...

  6. JAVA Eclipse的Android文件结构是怎么样的

    默认res目录下面存放了界面需要的布局和图片文件,之所以图片分为hdpi,ldpi,mdpi这些,是为了不同的设备准备的(高/中/低分辨率的图片)   Bin目录类似于VS的debug或者releas ...

  7. ps快捷键记录

    alt+delete  前景色填充 ctrl+delete  背景色填充 alt+shift+鼠标调节  变换选取,做圆环 ctrl+t  自由变换 alt+鼠标拖动  快捷复制某区域 delete ...

  8. memcpy( )的使用以及迭代器的使用

    memcpy() -- 拷贝内存内容 相关函数: bcopy(), memccpy(), memmove(), strcpy(), strncpy() 表头文件: #include <strin ...

  9. Android自动滚动 轮播循环的ViewPager

    主要介绍如何实现ViewPager自动播放,循环滚动的效果及使用.顺便解决ViewPager嵌套(ViewPager inside ViewPager)影响触摸滑动及ViewPager滑动速度设置问题 ...

  10. Skia构建系统与编译脚本分析

    分析下Skia的构建系统,详细编译过程參看Windows下从源代码编译Skia.这里以ninja为例来分析.运行以下三条命令就能够完毕编译: SET "GYP_GENERATORS=ninj ...