// Evict based on the number of entries in the cache // 根据缓存的计数进行驱逐 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .maximumSize(10_000) .build(key -> createExpensiveGraph(key));
// Evict based on the number of vertices in the cache // 根据缓存的权重来进行驱逐(权重只是用于确定缓存大小,不会用于决定该缓存是否被驱逐) LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .maximumWeight(10_000) .weigher((Key key, Graph graph) -> graph.vertices().size()) .build(key -> createExpensiveGraph(key));
// Evict based on a fixed expiration policy // 基于固定的到期策略进行退出 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key)); LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key));
// Evict based on a varying expiration policy // 基于不同的到期策略进行退出 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .expireAfter(newExpiry<Key, Graph>() { @Override publiclongexpireAfterCreate(Key key, Graph graph, long currentTime) { // Use wall clock time, rather than nanotime, if from an external resource longseconds= graph.creationDate().plusHours(5) .minus(System.currentTimeMillis(), MILLIS) .toEpochSecond(); return TimeUnit.SECONDS.toNanos(seconds); }
@Override publiclongexpireAfterUpdate(Key key, Graph graph, long currentTime, long currentDuration) { return currentDuration; }
@Override publiclongexpireAfterRead(Key key, Graph graph, long currentTime, long currentDuration) { return currentDuration; } }) .build(key -> createExpensiveGraph(key));
我们可以将缓存的驱逐配置成基于垃圾回收器。将 key 和 value 配置为弱引用或只将值配置成软引用。
1 2 3 4 5 6 7 8 9 10 11 12 13
// Evict when neither the key nor value are strongly reachable // 当key和value都没有引用时驱逐缓存 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .weakKeys() .weakValues() .build(key -> createExpensiveGraph(key));
// Evict when the garbage collector needs to free memory // 当垃圾收集器需要释放内存时驱逐 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .softValues() .build(key -> createExpensiveGraph(key));