美文网首页
Guava缓存报错returned null for key

Guava缓存报错returned null for key

作者: 卡萨布兰卡ginger | 来源:发表于2019-12-20 15:00 被阅读0次

Guava

首先,Guava是什么?其实也就是一个Java的第三方工具,有集合、缓存、字符串等功能;

问题

com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key XXXX.

    at com.google.common.cache.LocalCache$Segment.getAndRecordStats(LocalCache.java:2348)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2318)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.google.guava.cache.GuavaRefreshWhenCacheIsNullTest.testGuavaRefreshWhenCacheIsNullThrowsException(GuavaRefreshWhenCacheIsNullTest.java:49)

分析问题,由于使用了refreshAfterWrite的功能,如果key取出来为空则会报错,这个功能一个重要的工作就是在2次获取同一个key时,且key到了该refresh的时间,就会后台异步刷新,如果刷新这个key得到了新值,就会覆盖key对应的旧值;如果获取到的key为null,不知道是该刷新还是有异常

解决问题

  1. 可以捕获 CacheLoader$InvalidCacheLoadException 这个异常,return null
  1. 避免传入缓存null值,使用Optional等类,在key传入之前,就避免掉value

相关文章

网友评论

      本文标题:Guava缓存报错returned null for key

      本文链接:https://www.haomeiwen.com/subject/xvhinctx.html