JDK1.8 ConcurrentHashMap

JDK1.8的ConcurrentHashMap采用CAS和synchronized实现线程安全,具有更小的锁粒度。它使用node数组+链表+红黑树的数据结构,避免了Hashtable的效率低问题。在扩容时,将table分成多个部分并分配给不同线程,通过ForwardingNode协调并发操作。get、put和remove操作各有特点,如put时遇到扩容会参与扩容,get操作无需加锁,而remove操作需要头插法删除节点。
摘要由CSDN通过智能技术生成

在这里插入图片描述

hashmap:线程不安全
hashtable:通过synchronized保证线程安全但效率低。强一致性
ConcurrentHashMap:弱一致性

数据结构

ConcurrentHashMap为node数组+链表+红黑树。约等于hashmap

//第一次使用时初始化,大小2^n
transient volatile Node<K,V>[] table;

static class Node<K,V> implements Map.Entry<K,V> {
   
    final int hash;
    final K key;
    volatile V val;//不允许value改变值,避免加锁
    volatile Node<K,V> next;//不能改变next,只能头插
}

key和value不能为null
hashmap可以为null,通过containsKey()处理歧义,区别值为null还是值不存在
ConcurrentHashMap是并发的,get和containsKey并不是原子操作,所以无法区别歧义

JDK1.8 中采用CAS + synchronized,锁首节点,粒度更小

// jdk1.7分段segment加锁,跨段操作时,按顺序锁定全部段,按顺序解锁。
//继承ReentrantLock加锁解锁,保证每个 Segment 是线程安全
static class Segment<K,
ConcurrentHashMap is a thread-safe implementation of Map interface that allows concurrent access to the map from multiple threads without any data inconsistency or race condition. It was introduced in Java 5 and has been improved in Java 6 and Java 7. Some of the key features of ConcurrentHashMap are: - It is highly concurrent and supports high throughput. - It allows multiple threads to read and write the map concurrently without any blocking. - It provides better performance than Hashtable and synchronizedMap. - It supports high concurrency level with a tunable concurrency level that can be set during initialization. - It provides various methods for bulk operations such as putAll, clear, and replaceAll. - It supports atomic operations such as putIfAbsent, remove, and replace. In JDK 1.8, ConcurrentHashMap has been further improved with the addition of new methods and enhancements such as: - forEach() method: This method allows you to iterate over the key-value pairs in the map and perform an action on each of them. - compute() and computeIfAbsent() methods: These methods allow you to update the value of an existing key or add a new key-value pair to the map with a computed value. - merge() method: This method allows you to merge the values of two keys in the map using a specified function. - Improved scalability: The internal data structure and algorithms of ConcurrentHashMap have been improved to support better scalability and reduce contention among threads. Overall, ConcurrentHashMap is a highly efficient and scalable implementation of Map interface that is well-suited for concurrent applications with high throughput and low contention.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值