I created a cache with the following parameters:
cacheTempFiles = CacheBuilder.newBuilder().maximumSize(250).expireAfterWrite(15, TimeUnit.SECONDS).removalListener(new RemovalListener<String, Path>()
{
@Override
public void onRemoval(RemovalNotification<String, Path> notification)
{
deleteTemporaryFile(notification.getValue());
}
}).build();
Moreover, I'm calling every 2 minutes cacheTempFiles.cleanUp();
. However, it seems that onRemoval
is never called.
What is missing in my implementation?
It definitely should work, see example below:
@Test
public void shouldCallRemovalListener() {
AtomicInteger counter = new AtomicInteger();
MutableClock clock = MutableClock.epochUTC();
Ticker ticker = new Ticker() {
@Override
public long read() {
return TimeUnit.MILLISECONDS.toNanos(clock.millis());
}
};
Path tmpPath = Path.of("/tmp");
Cache<String, Path> cacheTempFiles = CacheBuilder.newBuilder()
.ticker(ticker)
.maximumSize(250)
.expireAfterWrite(15, TimeUnit.SECONDS)
.removalListener(
(RemovalNotification<String, Path> notification) ->
System.out.println(String.format(
"Delete '%s -> %s' (%d times)",
notification.getKey(), notification.getValue(), counter.incrementAndGet())))
.build();
cacheTempFiles.put("tmp", tmpPath);
assertThat(cacheTempFiles.asMap()).containsOnly(Assertions.entry("tmp", tmpPath));
assertThat(counter).hasValue(0);
clock.add(Duration.ofSeconds(20));
cacheTempFiles.cleanUp();
assertThat(cacheTempFiles.asMap()).isEmpty();
assertThat(counter).hasValue(1);
}
Passes and outputs Delete 'tmp -> /tmp' (1 times)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.