Why ConcurrentHashMap is better than Hashtable and just as good as a HashMap

ConcurrentHashMap相较于Hashtable提供了更高效的并发访问机制。它通过维护一系列锁来替代全局锁,允许多个线程同时修改不同桶的数据,从而减少等待时间并提高整体性能。在高负载下,这种设计可以显著改善响应时间和服务器效率。

Original from Why ConcurrentHashMap is better than Hashtable and just as good as a HashMap

ConcurrentHashMap is a pretty ignored class. Not many people know about it and not many people care to use it. The class offers a very robust and fast (comparatively, we all know java concurrency isn’t the fastest) method of synchronizing a Map collection.
I have read a few comparisons of HashMap and ConcurrentHashMap on the web. Let me just say that they’re totally wrong. There is no way you can compare the two, one offers synchronized methods to access a map while the other offers no synchronization whatsoever. What most of us fail to notice is that while our applications, web applications especially, work fine during the development & testing phase, they usually go tits up under heavy (or even moderately heavy) load. This is due to the fact that we expect our HashMap’s to behave a certain way but under load they usually misbehave.
Hashtable ’s offer concurrent access to their entries, with a small caveat, the entire map is locked to perform any sort of operation . While this overhead is ignorable in a web application under normal load, under heavy load it can lead to delayed response times and overtaxing of your server for no good reason.
This is where ConcurrentHashMap’s step in. They offer all the features of Hashtable with a performance almost as good as a HashMap. ConcurrentHashMap’s accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map . This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks.
Retrieval operations on a ConcurrentHashMap do not block unless the entry is not found in the bucket or if the value of the entry is null. In such a case the map synchronizes on the bucket and then tries to look for the entry again just in case the entry was put or removed right after the get in synchronized mode.
Removal operations do require a bit of overhead. All removal operations require the chain of elements before and after to be cloned and joined without the removed element. Since the value of the map key is volatile (not really, the value of the inner Entry class is volatile) if a thread already traversing the bucket from which a value is removed reaches the removed element, it automatically sees a null value and knows to ignore such a value.
Traversal in a ConcurrentHashMap does not synchronize on the entire map either. Infact traversal does not synchronize at all except under one condition. The internal LinkedList implementation is aware of the changes to the underlying collection. If it detects any such changes during traversal it synchronizes itself on the bucket it is traversing and then tries to re-read the values. This always insures that while the values recieved are always fresh, there is minimalistic locking if any.
Iteration over a ConcurrentHashMap are a little different from those offered by other collections. The iterators are not fail-fast in the sense that they do not throw a ConcurrentModificationException. They also do not guarantee that once the iterator is created it will list/show all elements that are added after its creation. The iterators do however guarantee that any updates or removal of items will be reflected correctly in their behaviour. They also guarantee that no element will be returned more than once while traversal.
In conclusion, give it a try, replace some Hashtable’s in your application with ConcurrentHashMap and see how they perform under load. The two are interchangeable so it shouldn’t be hard to update your app. Happy changing!

内容概要:本文档是一份关于交换路由配置的学习笔记,系统地介绍了网络设备的远程管理、交换机与路由器的核心配置技术。内容涵盖Telnet、SSH、Console三种远程控制方式的配置方法;详细讲解了VLAN划分原理及Access、Trunk、Hybrid端口的工作机制,以及端口镜像、端口汇聚、端口隔离等交换技术;深入解析了STP、MSTP、RSTP生成树协议的作用与配置步骤;在路由部分,涵盖了IP地址配置、DHCP服务部署(接口池与全局池)、NAT转换(静态与动态)、静态路由、RIP与OSPF动态路由协议的配置,并介绍了策略路由和ACL访问控制列表的应用;最后简要说明了华为防火墙的安全区域划分与基本安全策略配置。; 适合人群:具备一定网络基础知识,从事网络工程、运维或相关技术岗位1-3年的技术人员,以及准备参加HCIA/CCNA等认证考试的学习者。; 使用场景及目标:①掌握企业网络中常见的交换与路由配置技能,提升实际操作能力;②理解VLAN、STP、OSPF、NAT、ACL等核心技术原理并能独立完成中小型网络搭建与调试;③通过命令示例熟悉华为设备CLI配置逻辑,为项目实施和故障排查提供参考。; 阅读建议:此笔记以实用配置为主,建议结合模拟器(如eNSP或Packet Tracer)动手实践每一条命令,对照拓扑理解数据流向,重点关注VLAN间通信、路由选择机制、安全策略控制等关键环节,并注意不同设备型号间的命令差异。
HashMap 是一种常用的数据结构,基于哈希表实现。它采用数组和链表(或红黑树)组合的数据结构。数组作为主体存储结构,每个数组元素被称为一个桶(bucket)。当有元素插入时,会根据元素的哈希值计算出在数组中的位置。如果多个元素的哈希值相同,就会产生哈希冲突,这些元素会以链表的形式存储在同一个桶中。当链表长度超过一定阈值(通常为 8),且数组长度达到 64 时,链表会转换为红黑树,以提高查找效率 [^1]。 Hashtable 同样基于哈希表实现,其数据结构与 HashMap 类似,也是采用数组加链表的方式。不过 Hashtable 是线程安全的,它对几乎所有的方法都进行了同步处理。这意味着在多线程环境下,同一时间只能有一个线程对 Hashtable 进行写操作,虽然保证了线程安全,但在性能上会有一定的损耗 [^2]。 ConcurrentHashMap 在不同的 JDK 版本中数据结构有所不同。在 JDK 7 中,ConcurrentHashMap 采用分段锁的方式,它将整个数据分成多个段(Segment),每个段相当于一个小的 Hashtable,都有自己独立的锁。不同的段可以被不同的线程同时访问,这样就提高了并发性能。每个段内部是数组加链表的结构。而在 JDK 8 中,ConcurrentHashMap 摒弃了分段锁的设计,直接采用了 CAS(无锁算法) + synchronized。它的数据结构和 HashMap 类似,也是数组加链表(或红黑树)。在插入、删除、查找等操作时,会使用 CAS 操作来保证并发的安全性,当发生哈希冲突时,同样会以链表或红黑树的形式存储元素 [^2]。 ```java // 下面是简单的 HashMapHashtableConcurrentHashMap 的创建和使用示例 import java.util.HashMap; import java.util.Hashtable; import java.util.concurrent.ConcurrentHashMap; public class MapExample { public static void main(String[] args) { // 创建 HashMap HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("apple", 1); hashMap.put("banana", 2); // 创建 Hashtable Hashtable<String, Integer> hashtable = new Hashtable<>(); hashtable.put("cherry", 3); hashtable.put("date", 4); // 创建 ConcurrentHashMap ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>(); concurrentHashMap.put("elderberry", 5); concurrentHashMap.put("fig", 6); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值