[英]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:这给了你一对锁:
Despite the names, there is no reason these locks have to be used for reading and writing specifically:尽管有这些名称,但没有理由必须将这些锁专门用于读写:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.