为什么HashMap线程不安全,Hashtable和ConcurrentHashMap线程安全
HashMap源码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
HashMap.Node<K,V>[] tab; HashMap.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)
tab[i] = newNode(hash, key, value, null);
else {
HashMap.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 HashMap.TreeNode)
e = ((HashMap.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;
}
Hashtable源码
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.
Hashtable.Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Hashtable.Entry<K,V> entry = (Hashtable.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;
}
ConcurrentHashMap源码
public V put(K key, V value) {
return putVal(key, value, false);
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (ConcurrentHashMap.Node<K,V>[] tab = table;;) {
ConcurrentHashMap.Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new ConcurrentHashMap.Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
// 节点上锁,这里的节点可以理解为hash值相同组成的链表的头节点,锁的粒度为头节点。
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (ConcurrentHashMap.Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
ConcurrentHashMap.Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new ConcurrentHashMap.Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof ConcurrentHashMap.TreeBin) {
ConcurrentHashMap.Node<K,V> p;
binCount = 2;
if ((p = ((ConcurrentHashMap.TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
为什么HashMap线程不安全,Hashtable和ConcurrentHashMap线程安全的更多相关文章
- HashMap、HashTable 和 ConcurrentHashMap 线程安全问题
一.HashMap HashMap 是线程不安全的. JDK 1.7 HashMap 采用数组 + 链表的数据结构,多线程背景下,在数组扩容的时候,存在 Entry 链死循环和数据丢失问题. JDK ...
- HashMap、HashTable、ConcurrentHashMap、HashSet区别 线程安全类
HashMap专题:HashMap的实现原理--链表散列 HashTable专题:Hashtable数据存储结构-遍历规则,Hash类型的复杂度为啥都是O(1)-源码分析 Hash,Tree数据结构时 ...
- 【转】HashMap、TreeMap、Hashtable、HashSet和ConcurrentHashMap区别
转自:http://blog.csdn.net/paincupid/article/details/47746341 一.HashMap和TreeMap区别 1.HashMap是基于散列表实现的,时间 ...
- HashMap HashTable和ConcurrentHashMap的区别
HashMap和Hashtable都实现了Map接口,其主要的区别有:线程安全性,同步(synchronization),以及效率. HashMap和Hashtable基本上没啥区别,除了HashMa ...
- HashMap,HashTable,ConcurrentHashMap异同比较
0. 前言 HashMap和HashTable的区别一种比较简单的回答是: (1)HashMap是非线程安全的,HashTable是线程安全的. (2)HashMap的键和值都允许有null存在,而H ...
- HashMap、Hashtable、ConcurrentHashMap的原理与区别(简述)
HashTable 底层数组+链表实现,无论key还是value都不能为null,线程安全,实现线程安全的方式是在修改数据时锁住整个HashTable,效率低,ConcurrentHashMap做了相 ...
- HashMap、Hashtable、ConcurrentHashMap面试总结
原文链接:https://www.cnblogs.com/hexinwei1/p/10000779.html 小总结 HashMap.Hashtable.ConcurrentHashMap HashM ...
- HashMap、HashTable与ConcurrentHashMap区别
线程不安全的HashMap 在多线程环境下,使用HashMap进行put操作会引起死循环,导致CPU利用率接近100%,所以在并发情况下不能使用HashMap.例如,执行如下代码会引起死循环. fin ...
- HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的原理和区别
HashMap 是否是线程安全的,如何在线程安全的前提下使用 HashMap,其实也就是HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的 ...
随机推荐
- (1)wr703n刷openwrt智能控制--配置wifi
下载winscp和putty这两个软件:再刷到openwrt,通过winscp软件可以图形化修改配置文件“/etc/config/network”就可以上网了,再查找如何安装luci界面,就可以在pu ...
- 13 在 Django REST framework 善用 SerializerMethodField方法
01-使用SerializerMethodField 来优化不必要的查询 class RepairQueueSerializer(serializers.ModelSerializer): # rq_ ...
- day06(深浅拷贝,元组,字典,集合)
1,今日内容: 1.深浅拷贝:**** 2.元组 - 元组可以存放可变类型 *** 3.字典:***** -- 增删改查 -- 常用方法 4.集合:** -- 集合运算 5.数据类型的相互转化 *** ...
- MySQL--7种join连接
一,定义: 1)LEFT JOIN / LEFT OUTER JOIN:左外连接 左向外连接的结果集包括:LEFT OUTER子句中指定的左表的所有行,而不仅仅是连接列所匹配的行.如果左表的某行在右表 ...
- c#使用资源文件完成国际化
路径结构如下 namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void Te ...
- git和github的学习
摘要:Git是个实用而流行的工具,我在网上找了很多教程,发现很多扯来扯去的,难消化,难吸收,而廖雪峰老师的这个教程最好,由浅入深,一步一步跟着做,记录巩固下.原作网址:https://www.liao ...
- centos7和centos6通过yum安装JDK1.8
centos7和centos6通过yum安装JDK1.8 查看JDK的安装路径# java -version============================查看Linux系统版本信息# cat ...
- SpringBoot配置日志logback
1.这里我们选择logback,首先加入pom依赖 <dependency> <groupId>ch.qos.logback</groupId> <artif ...
- IFE第一天
我也不知道自己到底能坚持多少天,希望66天可以坚持下来,flag在此. 第一天的知识大概就是了解一些基本概念. Web: 基于HTTP协议,利用浏览器访问网站. HTML 大概就是告诉浏览器我有一个什 ...
- Debian社区群龙无首
导读 前两天有过消息 Debian 包维护者 Michael Stapelberg 因对 Debian 社区的现状不满而宣布退出 Debian 的维护,该消息引发了人们对于 Debian 的担忧.11 ...