什么情况下用ConcurrentHashMap
程序员文章站
2022-04-20 14:48:10
...
很多同事都了解了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; }