什么情况下用ConcurrentHashMap

本文对比HashMap与ConcurrentHashMap的特点,介绍了多线程环境下使用ConcurrentHashMap的优势,并通过实例展示了如何利用其提供的方法来实现线程安全的数据更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多同事都了解了HashMap和ConcurrentHashMap的原理,并且也看了两个类的源码,但是还是不知道在什么情况下使用ConcurrentHashMap。

1,在多线程并发向HashMap中put数据时,就需要把HashMap换成ConcurrentHashMap。

(原因为并发向HashMap中put数据会出现死循环,导致CPU使用率暴增。参考参考:http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html

2,在业务中可以使用ConcurrentMap接口中定义的方法解决并发问题时。

public interface ConcurrentMap<K, V> extends Map<K, V> {
    V putIfAbsent(K key, V value);
    boolean remove(Object key, Object value);
    boolean replace(K key, V oldValue, V newValue);
    V replace(K key, V value);
}

 

举个例子

private final Map<String, Long> wordCounts = new ConcurrentHashMap<>();
 
public long increase(String word) {
    Long oldValue = wordCounts.get(word);
    Long newValue = (oldValue == null) ? 1L : oldValue + 1;
    wordCounts.put(word, newValue);
    return newValue;
}

 替换为

private final ConcurrentMap<String, Long> wordCounts = new ConcurrentHashMap<>();
 
public long increase(String word) {
    Long oldValue, newValue;
    while (true) {
        oldValue = wordCounts.get(word);
        if (oldValue == null) {
            // Add the word firstly, initial the value as 1
            newValue = 1L;
            if (wordCounts.putIfAbsent(word, newValue) == null) {
                break;
            }
        } else {
            newValue = oldValue + 1;
            if (wordCounts.replace(word, oldValue, newValue)) {
                break;
            }
        }
    }
    return newValue;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值