0

I'm setting up my cache like that:

Cache<String,MyClass> cache = CacheBuilder.newBuilder().expireAfterAccess( 16l, TimeUnit.MINUTES ).build()

and

class MyClass {
  String name
  boolean canExpire
}

I want the instances with canExpire = true be expired regurarly, but those with false not.

Is there any standard / straight-forward way to achieve such behaviour?

4

1 回答 1

0

您可以使用expireAfterWrite计划任务重新放置不应过期的条目:

Cache<String, MyClass> cache = CacheBuilder.newBuilder()
        .expireAfterAccess(16L, TimeUnit.MINUTES)
        .expireAfterWrite(16L, TimeUnit.MINUTES)
        .build();

ScheduledExecutorService exitingScheduledExecutorService = MoreExecutors
        .getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
Runnable command = () -> cache.putAll(Maps.filterValues(cache.asMap(), myClass ->
        !myClass.canExpire)));
exitingScheduledExecutorService.scheduleWithFixedDelay(command, 0, 15L, TimeUnit.MINUTES);
于 2017-02-01T16:54:06.267 回答