测试 – Guava Ticker Cache过期

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,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")); 

}

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...