我有一個用作快取的類,它使用 Map(HashMap 或 ConcurrentHashMap),我想在執行每個新的(http)請求之前清除我的 Map,例如
@Component
public Class MyCache {
Map cache = new ConcurrentHashMap();
get(key) {
cache.computeIfAbsent(key, fetchFromDB())
}
clearCache() {
cache.clear()
}
}
@Controller
public Class MyController {
@Autowired
MyCache myCache
@Get
Response getInfo(ids) {
// give me a fresh cache at beginning of every new request
myCache.clearCache()
// load and fetch from myCache of current request
ids.foreach(id -> {
myCache.get(id)
})
}
}
上面的代碼思路是
- 當有新請求進入時最初重置快取
- 然后對于輸入的所有 id(可能是數百個),從快取中獲取
- 如果相同的 id 已經存盤在快取中,我們不需要重新呼叫 fetchFromDB。
一切都使用單執行緒在本地作業,但是當使用 2 個或更多執行緒呼叫時,有可能在 thread1 的執行程序中,thread2 啟動并且它會呼叫myCache.clearCache(),不知何故,我的 thread1 突然發現 myCache 中所有已處理的專案都沒有存盤任何東西了。
- 原因是因為我的地圖在類中是單例的(例如 MyCache、Controller),即使每個請求都處理自己的執行緒,它們也會對同一個實體執行操作
- What's the best way that I would fix this issue if I still wants to get a clean cache for each request comes in? Anyway I can detect if there might be other threads still executing before my current thread clearCache()
uj5u.com熱心網友回復:
我通過遵循 Google Guava Cache 如何與 Concurrent Hashmap 和 Reentrance lock as Segment 一起作業來解決它
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442902.html
標籤:java multithreading spring-boot race-condition
下一篇:如何在特定執行緒上獲取物件?
