简体   繁体   English

锁定 ConcurrentHashMap 以进行独占读取

[英]Locking ConcurrentHashMap for an exclusive read

I have several threads that save information to my ConcurrentHashMap<K,V> .我有几个线程可以将信息保存到我的ConcurrentHashMap<K,V> I'm supposed to take a snapshot of the whole Map in a parent thread, process the information in it and eventually empty it from all values and keys.我应该在父线程中拍摄整个 Map 的快照,处理其中的信息并最终从所有值和键中清空它。

How can I make sure that during the read (in the parent thread), it is not gonna be updated by any child-threads writing to it until I'm done with it?我如何确保在读取期间(在父线程中),在我完成之前不会被任何写入它的子线程更新? Is it possible to lock this data structure with a semaphore or a mutex?是否可以用信号量或互斥锁锁定这个数据结构?

Try something like this.尝试这样的事情。 Using a monitor to guard the map field so when you're taking the snapshot no one else can put values inside it.使用监视器保护 map field ,因此当您拍摄快照时,没有其他人可以将值放入其中。

public class Example<K, V> {
    private final Map<K, V> map = new HashMap<>();
    private final Object monitor = new Object();

    public Object snapshot() {
        synchronized (monitor) {
            // take the snapshot and return it
        }
    }

    public V put(K key, V value) {
        synchronized (monitor) {
            return map.put(key, value);
        }
    }
}

Also in this example you can simplify it by using a simple HashMap instead of a ConcurrentHashMap because you have the monitor guarding accesses to that field.同样在此示例中,您可以通过使用简单的HashMap而不是ConcurrentHashMap来简化它,因为您有监视器保护对该字段的访问。

Use a ReadWriteLock .使用ReadWriteLock

This gives you a pair of locks:这给了你一对锁:

  • A read lock, which many threads can acquire at the same time一个读锁,许多线程可以同时获取
  • A write lock, which only one thread can hold, and whilst held no thread can hold the read lock.写锁,只有一个线程可以持有,在持有期间没有线程可以持有读锁。

Despite the names, there is no reason these locks have to be used for reading and writing specifically:尽管有这些名称,但没有理由必须将这些锁专门用于读写:

  • Acquire (and release) the read lock for threads that are updating the map获取(并释放)正在更新 map 的线程的读锁
  • Acquire (and release) the write lock for the thread which has to see the whole map at once.获取(并释放)必须立即查看整个 map 的线程的写锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM