并发 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);
}实现类
| 实现 | 底层 | 特点 |
|---|---|---|
| ConcurrentHashMap | CAS + synchronized | 高并发 Map |
| ConcurrentSkipListMap | 跳表 | 高并发 + 排序 |
| ConcurrentNavigableMap | — | SortedMap 的并发版 |
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。
