
本文将深入探讨在Java中使用ConcurrentHashMap时进行外部同步的问题。ConcurrentHashMap本身已提供高效的并发控制机制,通过compute等方法实现原子更新。对ConcurrentHashMap实例进行外部同步,会失去其并发优势,并可能导致代码维护困难。本文将深入分析这一问题,并提供避免外部同步、利用ConcurrentHashMap内置并发机制的实践指导。
ConcurrentHashMap是Java并发包java.util.concurrent中的一个重要类,它提供了线程安全且高效的哈希表实现。与Hashtable或使用Collections.synchronizedMap()包装的HashMap不同,ConcurrentHashMap采用分段锁(Segment Locking)机制,允许在不同段上进行并发读写操作,从而显著提高并发性能。
直接对ConcurrentHashMap实例进行synchronized同步块操作,会锁住整个Map,导致所有线程必须等待锁释放才能进行读写操作。这完全违背了使用ConcurrentHashMap的初衷,使其并发性能退化为与同步的HashMap相当。SonarLint等代码质量检测工具通常会发出警告,指出这种做法可能存在问题。
以下代码示例展示了不推荐的做法:
立即学习“Java免费学习笔记(深入)”;
import java.util.concurrent.ConcurrentHashMap;
public class MyClass<K, V> {
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
public V get(K key) {
return map.computeIfAbsent(key, this::calculateNewElement);
}
protected V calculateNewElement(K key) {
V result;
// 不推荐:对 ConcurrentHashMap 实例进行外部同步
synchronized(map) {
// 计算新元素(赋值给 result)
// 包含遍历整个 map 的操作
// 以及可能对同一个 map 进行其他修改
result = calculate(key); // 假设的计算方法
}
return result;
}
private V calculate(K key){
// 这里是你的计算逻辑,可能会遍历map并进行修改
return null; // 占位符,需要替换成实际的计算结果
}
}SonarLint等工具会提示如下警告:
Multi-threading - Synchronization performed on util.concurrent instancefindbugs:JLM_JSR166_UTILCONCURRENT_MONITORENTERThis method performs synchronization on an object that is an instance of a class from the java.util.concurrent package (or its subclasses). Instances of these classes have their own concurrency control mechanisms that are orthogonal to the synchronization provided by the Java keyword synchronized. For example, synchronizing on an AtomicBoolean will not prevent other threads from modifying the AtomicBoolean.Such code may be correct, but should be carefully reviewed and documented, and may confuse people who have to maintain the code at a later date.
ConcurrentHashMap提供了诸如compute()、computeIfAbsent()、computeIfPresent()、merge()等原子操作,可以在保证线程安全的前提下,对Map中的数据进行复杂的操作。这些方法通过锁住特定Segment来实现细粒度的并发控制,避免了全局锁带来的性能瓶颈。
以下代码示例展示了如何使用computeIfAbsent()实现原子更新:
import java.util.concurrent.ConcurrentHashMap;
public class MyClass<K, V> {
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
public V get(K key) {
// 使用 computeIfAbsent 原子地计算并添加新元素
return map.computeIfAbsent(key, this::calculateNewElement);
}
protected V calculateNewElement(K key) {
// 计算新元素,无需手动同步
V result = calculate(key); // 假设的计算方法
return result;
}
private V calculate(K key){
// 这里是你的计算逻辑,可能会遍历map并进行修改
// 注意:calculate方法内部不应该直接修改map,否则可能导致并发问题
return null; // 占位符,需要替换成实际的计算结果
}
}注意: 在calculate方法中,如果需要遍历map,应尽量避免直接修改map。如果必须修改,则考虑使用ConcurrentHashMap提供的原子更新方法,或者考虑使用其他更适合的并发数据结构,如并发树(ConcurrentSkipListMap)或持久化集合。
如果每次更新都需要修改大量的节点,ConcurrentHashMap可能不是最佳选择。在这种情况下,可以考虑以下数据结构:
在使用ConcurrentHashMap时,应充分利用其内置的并发机制,避免不必要的外部同步。通过使用compute()等原子操作,可以实现高效且线程安全的并发更新。如果需要进行大量节点的修改,则应考虑使用其他更适合的数据结构。理解ConcurrentHashMap的内部工作原理,有助于编写出高效且易于维护的并发代码。
以上就是标题:Java ConcurrentHashMap 的外部同步问题与解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号