[英]How to clean ConcurrentHashMap in thread safe way
我有一个 ConcurrentHashMap oricginalCahce,其中多个线程从代码的许多地方同时写入。 我必须定期刷新 map,所以我在下面创建了 Map 的临时副本并清理了原始 Map
void flushcopyOfOriginalCache(String queueName) {
Map<Integer, Date> copyOfOriginalCache = null;
Object lock = getLastscheduledTimeUpdateLock(queueName);
//this lock is not aquired at the time of writing as the writing in taking place in many places of the code
synchronized (lock) {
//rechecking for whether expired or not
if (isOrigCacheExpired(queueName)) {
log.info("origCache Expired for queue {}", queueName);
if (orignalCache.containsKey(queueName)) {
copyOfOriginalCache = new ConcurrentHashMap<>(
orignalCache.get(queueName));
//How safe is below clean ??? as parallel writes might be going on orignalCache!
orignalCache.get(queueName).clear();
}
}
}
if (copyOfOriginalCache == null || copyOfOriginalCache.isEmpty()) {
return;
}
//Below is expenssive DB operations on with data in copyOfOriginalCache
}
如何确保这个干净的方法不应该删除正在写入的条目。 请指导。
对于 ConcurrentHashMap,您可以使用 computeIfPresent 和谓词canDeleted(Value v)
concurrentHashmap.forEach((key, value) ->
concurrentHashmap.computeIfPresent(key, (t, s) -> (canDeleted(s) ? null : s)))
这是线程安全的并且易于实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.