hashMap的线程不安全
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的线程不安全的更多相关文章
- HashMap为什么线程不安全(hash碰撞与扩容导致)
一直以来都知道HashMap是线程不安全的,但是到底为什么线程不安全,在多线程操作情况下什么时候线程不安全? 让我们先来了解一下HashMap的底层存储结构,HashMap底层是一个Entry数组,一 ...
- 为什么说 HashMap 是非线程安全的?
我们在学习 HashMap 的时候,都知道 HashMap 是非线程安全的,同时我们知道 HashTable 是线程安全的,因为里面的方法使用了 synchronized 进行同步. 但是 HashM ...
- Java基础知识强化之集合框架笔记80:HashMap的线程不安全性的体现
1. HashMap 的线程不安全性的体现: 主要是下面两方面: (1)多线程环境下,多个线程同时resize()时候,容易产生死锁现象.即:resize死循环 (2)如果在使用迭代器的过程中有其他线 ...
- HashMap变成线程安全方法
我们都知道.HashMap是非线程安全的(非同步的).那么怎么才能让HashMap变成线程安全的呢? 我认为主要可以通过以下三种方法来实现: 1.替换成Hashtable,Hashtable通过对整个 ...
- Java并发基础08. 造成HashMap非线程安全的原因
在前面我的一篇总结(6. 线程范围内共享数据)文章中提到,为了数据能在线程范围内使用,我用了 HashMap 来存储不同线程中的数据,key 为当前线程,value 为当前线程中的数据.我取的时候根据 ...
- 面试官:小伙子,你给我说一下HashMap 为什么线程不安全?
前言:我们都知道HashMap是线程不安全的,在多线程环境中不建议使用,但是其线程不安全主要体现在什么地方呢,本文将对该问题进行解密. 1.jdk1.7中的HashMap 在jdk1.8中对HashM ...
- HashMap 为什么线程不安全?
作者:developer http://cnblogs.com/developer_chan/p/10450908.html 我们都知道HashMap是线程不安全的,在多线程环境中不建议使用,但是其线 ...
- 验证hashmap非线程安全
http://www.blogjava.net/lukangping/articles/331089.html final HashMap<String, String> firstHas ...
- HashMap非线程安全分析
通过各方资料了解,HashMap不是线程安全的,但是为什么不是线程安全的,在什么情况下会出现问题呢? 1. 下面对HashMap做一个实验,两个线程,并发写入不同的值,key和value相同,最后再看 ...
随机推荐
- 做dg时遇到的log_archive_dest、log_archive_dest_1、db_recovery_file_dest之间互相影响
前提:归档开启.默认不指定归档文件夹. 今晚遇到客户那里设置了闪回区和log_archive_dest.不停库做DG时,无法指定log_archive_dest_n參数,巨坑. .实验了下.结论例如以 ...
- HDU 1017 A Mathematical Curiosity (枚举水题)
Problem Description Given two integers n and m, count the number of pairs of integers (a,b) such tha ...
- vue install 注册组件
1.myPlugin.js文件 let MyPlugin = {}; MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或属性 Vue. ...
- 【经验】使用Profiler工具分析内存占用情况
Unity3D为我们提供了一个强大的性能分析工具Profiler.今天我们就使用Profiler来具体分析一下官方样例AngryBots的内存使用信息数据. 首先打开Profiler选择Memory选 ...
- mixare的measureText方法在频繁调用时抛出“referencetable overflow max 1024”的解决方式
这几天在搞基于位置的AR应用,採用了github上两款开源项目: mixare android-argument-reality-framework 这两个项目实现机制大致同样.我选取的是androi ...
- Node.app让Nodejs平台在iOS和OS X系统上奔跑
首先呢,欢迎大家去查看相同内容的链接:http://www.livyfeel.com/nodeapp/. 由于那个平台我用的markdown语法,我也懒得改动了,就这样黏贴过来了. 这是一个惊人的恐怖 ...
- 思维探索者:完善个人知识体系的重要性 Google只会告诉你结果
http://www.nowamagic.net/librarys/veda/detail/1711前面说了,人类解决问题大部分时候会习惯性地使用联想思维,简言之就是首先枚举你关于这个问题能够想到的所 ...
- ios 视图的旋转及应用
有时候,需要做出如下图所示的效果,这就需要用到视图的旋转了 1.首先将旋转的值由角度转换为弧度: #define degreesToRadinas(x) (M_PI * (x)/180.0) 注:M_ ...
- JavaScript 文件操作方法详解
可以通过浏览器在访问者的硬盘上创建文件,因为我开始试了一下真的可以,不信你把下面这段代码COPY到一个HTML文件当中再运行一下! <script language="JavaScri ...
- git 操作分支
1. git 查看本地分支:git branch 2. git 查看所有分支:git branch -a 3. git 新建本地分支:git branch branchName 4. git 新建分支 ...