可以合并weakValues()和expireAfterAccess()吗?

时间:2016-05-31 20:49:18

标签: guava google-guava-cache

我想做这样的事情:

 CacheBuilder
            .newBuilder()
            .maximumSize(CONFIG.cacheMaxSize())
            .expireAfterAccess(CONFIG.cacheTimeout(),
                                CONFIG.cacheTimeUnit())
            .weakValues()
            .build(cacheLoader);

我期望的行为是,如果未引用该值且过期时间已过,则条目将仅过期。那这种用法是如何运作的?

2 个答案:

答案 0 :(得分:2)

不直接,因为只要没有对该对象的更强引用,就可以对弱值进行垃圾收集。然而,你可以做的是使用一个ForwardingCache支持两个独立的缓存,一个弱值缓存和一个定时到期缓存,这样基于时间的缓存就可以保存对象的强引用,从而将它保留在弱值缓存。它看起来像这样:

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中1}}在相关的加载方法中。

答案 1 :(得分:1)

不,如果未引用该值或过期时间已过,则条目将过期:

public class CacheBuilderIT {
    @Test
    public void expireAfterAccessWithWeakValues() throws InterruptedException {
        Cache<Object, Object> cache = CacheBuilder.newBuilder()
                .expireAfterAccess(500, MILLISECONDS)
                .weakValues()
                .build();
        Object key = new Object();
        Object value = new Object(); // keep a strong reference to the value
        cache.put(key, value);
        Thread.sleep(300);
        assert cache.getIfPresent(key) != null : "expiration occurred too quickly";
        Thread.sleep(300);
        assert cache.getIfPresent(key) != null : "last access did not reset expiration";
        Thread.sleep(1000);
        assert cache.getIfPresent(key) != null : "reference did not prevent expiration";
    }
}

Ouptut:

java.lang.AssertionError: reference did not prevent expiration