继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

com.google.common.cache.LocalCache类

Naison
关注TA
已关注
手记 5
粉丝 2
获赞 9

偶然看见这个类,是因为我们的缓存时基于这个类的idea来实现的,有一个缓存过期时间,觉着很好玩,就看看源码,最关键的就是:

@Nullable
ReferenceEntry<K, V> getLiveEntry(Object key, int hash, long now) {
  ReferenceEntry<K, V> e = getEntry(key, hash);
  if (e == null) {
    return null;
  } else if (map.isExpired(e, now)) {
    tryExpireEntries(now);
    return null;
  }
  return e;
}

这个有一句

map.isExpired(e, now)

如果为true,就直接返回null,简直是nice,这样再做软缓存的时候,例如@LocalCache这样的注解的时候,就可以指定缓存失效的时间了。

贴一下缓存判断失效的方法:

boolean isExpired(ReferenceEntry<K, V> entry, long now) {
  checkNotNull(entry);
  if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) {
    return true;
  }
  if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) {
    return true;
  }
  return false;
}


打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP