gpt4 book ai didi

java - Guava 缓存 RemovalListener 未调用

转载 作者:行者123 更新时间:2023-12-01 19:23:01 26 4
gpt4 key购买 nike

我使用以下参数创建了一个缓存:

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();

此外,我每 2 分钟调用一次 cacheTempFiles.cleanUp();。但是,似乎从未调用过onRemoval

我的实现中缺少什么?

最佳答案

它绝对应该有效,请参见下面的示例:

@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);
}

传递并输出删除'tmp ->/tmp'(1次)

关于java - Guava 缓存 RemovalListener 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59339275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com