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?

injecteer
  • 20,038
  • 4
  • 45
  • 89

1 Answers1

0

You can use expireAfterWrite with a scheduled task to re-put the entries that should not expire:

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);
mfulton26
  • 29,956
  • 6
  • 64
  • 88