gpt4 book ai didi

testing - Guava Ticker 缓存过期

转载 作者:行者123 更新时间:2023-11-28 19:43:37 24 4
gpt4 key购买 nike

Google Guava 教程说缓存过期可以用 Ticker 来测试

据我了解,我可以用它来强制快速过期。 我说得对吗

但是我在下面的代码中尝试过,但是没有用,有什么建议吗?

@Test
public void expireAfterWriteTestWithTicker() throws InterruptedException {
Ticker t = new Ticker() {
@Override
public long read() {
return TimeUnit.MILLISECONDS.toNanos(5);
}
};
//Use ticker to force expire in 5 millseconds
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(20, TimeUnit.MINUTES).ticker(t).build(loader);

cache.getUnchecked("hello");
assertEquals(1, cache.size());
assertNotNull(cache.getIfPresent("hello"));
//sleep
Thread.sleep(10);
assertNull(cache.getIfPresent("hello")); //failed

}

最佳答案

自己找答案

Ticker可以用来跳过时间,但不能跳过过期时间

class FakeTicker extends Ticker {

private final AtomicLong nanos = new AtomicLong();

/** Advances the ticker value by {@code time} in {@code timeUnit}. */
public FakeTicker advance(long time, TimeUnit timeUnit) {
nanos.addAndGet(timeUnit.toNanos(time));
return this;
}

@Override
public long read() {
long value = nanos.getAndAdd(0);
System.out.println("is called " + value);
return value;
}
}

@Test
public void expireAfterWriteTestWithTicker() throws InterruptedException {
FakeTicker t = new FakeTicker();

// Use ticker to force expire in 20 minute
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(20, TimeUnit.MINUTES).ticker(t).build(ldr);
cache.getUnchecked("hello");
assertEquals(1, cache.size());
assertNotNull(cache.getIfPresent("hello"));

// add 21 minutes
t.advance(21, TimeUnit.MINUTES);
assertNull(cache.getIfPresent("hello"));

}

关于testing - Guava Ticker 缓存过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29990788/

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