我實現了一個Object
緩存,像這樣:的Java:對垃圾收集賽車
// Dictionary with weak keys & values
private Map<Object, WeakReference<Object>> cache = new WeakHashMap<>();
private Object checkCache(Object obj) {
// If it's in the cache, returned the cached copy.
if (cache.containsKey(obj)) return cache.get(obj).get();
// Store it in, and return it.
cache.put(obj, new WeakReference<>(obj));
return obj;
}
圖片下面的比賽條件的場景:
cache.containsKey(obj)
回報true
- 的垃圾收集器開始並收集緩存中的對象。
null
被返回。
的問題是:
- 可這真的會發生? AFAIK GC可以在任何時間踢任何時間。
- Java GC可以禁用單個方法調用嗎?似乎不能阻止GC。
- 是否有任何解決方法?
在此先感謝!
您正在濫用'WeakHashMap'。 – SLaks
@SLaks請你詳細說明爲什麼? – MBlanc
在這種情況下,您既有弱鍵也有弱值。 –