[英]Is ConcurrentHashMap's computeIfAbsent thread safe, when nested?
我是使用Map的computeIfAbsent方法的新手。 我確實發現(根據Java文檔)整個方法調用是原子執行的。 我想知道(而不是確認)下面的代碼片段(在方法內部)是否會自動執行。
ConcurrentMap<RunMode, Map<LocalDate, Map<Integer, Set<DomainObject>>>> myCache = new ConcurrentHashmap<>();
公共無效addToCache(RunMode runMode,LocalDate bizDate,DomainObject bean){
Set<DomainObject> domainObjSet = myCache.computeIfAbsent(runMode, runModeMap-> new ConcurrentHashMap<>())
.computeIfAbsent(bizDate, bizDateMap-> new ConcurrentHashMap<>())
.computeIfAbsent(bean.getId(), domainSet-> Collections.synchronizedSet(new HashSet<>()).add(bean));
}
取決於您在此所說的原子性。
另一個線程可能會從myCache
獲取Map, myCache
該Map將看不到bizDate
條目。
如果要在所有線程獲取myCache
之前完全填充Map,則需要在myCache.computeIfAbsent
創建並填充myCache.computeIfAbsent
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.