オブジェクトへの強い参照がなくなるとすぐに弱い値をガベージ コレクションできるため、直接ではありません。ただしForwardingCache
、弱い値のキャッシュと有効期限のあるキャッシュの 2 つの個別のキャッシュを使用して、時間ベースのキャッシュがオブジェクトへの強い参照を保持し、それによってオブジェクトを弱い値のキャッシュに保持することができます。次のようになります。
public class WeakValuedExpiringCache<K, V> extends ForwardingCache<K, V> {
private final Cache<K, V> expiringCache;
private final Cache<K, V> weakCache;
public WeakValuedExpiringCache(CacheBuilder expiringSpec) {
expiringCache = expiringSpec.build();
weakCache = CacheBuilder.newBuilder().weakValues().build();
}
// weakCache is the canonical cache since it will hold values longer than
// expiration if there remain other strong references
protected Cache<K, V> delagate() {
return weakCache;
}
@override
public V get(K key, Callable<? extends V> valueLoader)
throws ExecutionException {
// repopulate the expiring cache if needed, and update the weak cache
V value = expiringCache.get(key, valueLoader);
weakCache.put(key, value); // don't call super.put() here
}
@Override
public void put(K key, V value) {
expiringCache.put(key, value);
super.put(key, value);
}
// Handle putAll(), cleanUp(), invalidate(), and invalidateAll() similarly
}
上記のForwardingLoadingCache
ように、関連するロード メソッドで.get()
から値をロードし、expiringCache
それ.put()
を にロードする必要があります。weakCache