[英]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.