测试 – Guava Ticker Cache过期

前端之家收集整理的这篇文章主要介绍了测试 – Guava Ticker Cache过期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Google Guava教程称缓存过期可以用 Ticker进行测试

根据我的理解,我可以用它来强制快速过期.我对吗?

但我试过以下代码,它没有用,有什么建议吗?

  1. @Test
  2. public void expireAfterWriteTestWithTicker() throws InterruptedException {
  3. Ticker t = new Ticker() {
  4. @Override
  5. public long read() {
  6. return TimeUnit.MILLISECONDS.toNanos(5);
  7. }
  8. };
  9. //Use ticker to force expire in 5 millseconds
  10. LoadingCache<String,String> cache = CacheBuilder.newBuilder()
  11. .expireAfterWrite(20,TimeUnit.MINUTES).ticker(t).build(loader);
  12.  
  13. cache.getUnchecked("hello");
  14. assertEquals(1,cache.size());
  15. assertNotNull(cache.getIfPresent("hello"));
  16. //sleep
  17. Thread.sleep(10);
  18. assertNull(cache.getIfPresent("hello")); //Failed
  19.  
  20. }

解决方法

只要自己找到答案

Ticker可用于跳过时间,但不能用于到期时间

  1. class FakeTicker extends Ticker {
  2.  
  3. private final AtomicLong nanos = new AtomicLong();
  4.  
  5. /** Advances the ticker value by {@code time} in {@code timeUnit}. */
  6. public FakeTicker advance(long time,TimeUnit timeUnit) {
  7. nanos.addAndGet(timeUnit.toNanos(time));
  8. return this;
  9. }
  10.  
  11. @Override
  12. public long read() {
  13. long value = nanos.getAndAdd(0);
  14. System.out.println("is called " + value);
  15. return value;
  16. }
  17. }
  1. @Test
  2. public void expireAfterWriteTestWithTicker() throws InterruptedException {
  3. FakeTicker t = new FakeTicker();
  4.  
  5. // Use ticker to force expire in 20 minute
  6. LoadingCache<String,TimeUnit.MINUTES).ticker(t).build(ldr);
  7. cache.getUnchecked("hello");
  8. assertEquals(1,cache.size());
  9. assertNotNull(cache.getIfPresent("hello"));
  10.  
  11. // add 21 minutes
  12. t.advance(21,TimeUnit.MINUTES);
  13. assertNull(cache.getIfPresent("hello"));
  14.  
  15. }

猜你在找的Java相关文章