至尊宝的传说
我会使用double buffering和读/写锁。双缓冲通过允许处理换出的映射来减少阻塞。使用读/写锁让我可以确定在我们交换后没有人仍在写入地图。class DoubleBufferedMap<K, V> extends AbstractMap<K, V> implements Map<K, V> { // Used whenever I want to create a new map. private final Supplier<Map<K, V>> mapSupplier; // The underlying map. private volatile Map<K, V> map; // My lock - for ensuring no-one is writing. ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); final Lock readLock = readWriteLock.readLock(); final Lock writeLock = readWriteLock.writeLock(); public DoubleBufferedMap(Supplier<Map<K, V>> mapSupplier) { this.mapSupplier = mapSupplier; this.map = mapSupplier.get(); } /** * Swaps out the current map with a new one. * * @return the old map ready for processing, guaranteed to have no pending writes. */ public Map<K,V> swap() { // Grab the existing map. Map<K,V> oldMap = map; // Replace it. map = mapSupplier.get(); // Take a write lock to wait for all `put`s to complete. try { writeLock.lock(); } finally { writeLock.unlock(); } return oldMap; } // Put methods must take a read lock (yeah I know it's weird) @Nullable @Override public V put(K key, V value) { try{ // Take a read-lock so they know when I'm finished. readLock.lock(); return map.put(key, value); } finally { readLock.unlock(); } } @Override public void putAll(@NotNull Map<? extends K, ? extends V> m) { try{ // Take a read-lock so they know when I'm finished. readLock.lock(); map.putAll(m); } finally { readLock.unlock(); } } @Nullable @Override public V putIfAbsent(K key, V value) { try{ // Take a read-lock so they know when I'm finished. readLock.lock(); return map.putIfAbsent(key, value); } finally { readLock.unlock(); } } // All other methods are simply delegated - but you may wish to disallow some of them (like `entrySet` which would expose the map to modification without locks). @Override public Set<Entry<K, V>> entrySet() { return map.entrySet(); } @Override public boolean equals(Object o) { return map.equals(o); } @Override public int hashCode() { return map.hashCode(); } // ... The rest of the delegators (left to the student)