Skip to content

并发 Map 接口与实现

并发 Map 接口

ConcurrentMap 接口扩展了 Map,添加了原子操作:

java
public interface ConcurrentMap<K, V> extends Map<K, V> {
    // key 不存在时才插入
    V putIfAbsent(K key, V value);

    // 只有 key 存在时才替换
    boolean replace(K key, V oldValue, V newValue);
    V replace(K key, V value);

    // 删除(原子操作)
    boolean remove(Object key, Object value);
}

实现类

实现底层特点
ConcurrentHashMapCAS + synchronized高并发 Map
ConcurrentSkipListMap跳表高并发 + 排序
ConcurrentNavigableMapSortedMap 的并发版

ConcurrentSkipListMap

ConcurrentHashMap 是无序的,ConcurrentSkipListMap 支持按键排序:

java
ConcurrentSkipListMap<String, Integer> sorted = new ConcurrentSkipListMap<>();

sorted.put("banana", 2);
sorted.put("apple", 1);
sorted.put("cherry", 3);

System.out.println(sorted.firstKey());   // apple(字典序)
System.out.println(sorted.lastKey());   // cherry
System.out.println(sorted.lowerKey("cherry")); // banana

总结

要点说明
ConcurrentHashMap高并发 Map,无序
ConcurrentSkipListMap高并发 + 排序 Map

一句话:并发 Map 的两个选择——要速度用 ConcurrentHashMap,要排序用 ConcurrentSkipListMap。


相关链接

基于 VitePress 构建