I would use double buffering
and a Read/Write lock.
Double buffering reduces holdups by allowing processing of the swapped-out map.
Using a Read/Write lock allows me to be certain that no-one is still writing to the map after we swap.
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)