如何不为Guava的LoadingCache添加空值?

时间:2015-06-16 11:50:59

标签: java xml caching xpath guava

我必须使用Guava's LoadingCache来缓存key => xpath expression和值xpath values的xpath值。

但问题是并非所有xpathes都有值。许多xpath值都有空值(如果要准确清楚,则为null)。

以下是代码段:

private LoadingCache<String, List<String>> cachedXpaths = CacheBuilder.newBuilder()
        .expireAfterWrite(3, TimeUnit.MINUTES)
        .maximumSize(1000)
        .concurrencyLevel(5)
        .weakKeys()
        .build(new CacheLoader<String, List<String>>() {
            @Override
            public List<String> load(String key) throws Exception {
                return createListByKey(key);
            }
        });

private static List<String> createListByKey(String key) throws Exception {
    List<String> values = null;
    try {
        values = instance.getXpathValues(key);
    } catch (XPathExpressionException ignore) {
    }
    return values;
}

结果我得到了:

testEncounterSection(com.epam.cdatest.section.EncountersSectionTest)  Time elapsed: 0.002 sec  <<< FAILURE!
com.google.common.util.concurrent.UncheckedExecutionException: com.epam.cdatest.exceptions.XpathHasEmptyValueException
    at com.epam.cdatest.parsers.XpathEvaluator.getXpathValues(XpathEvaluator.java:123)
    at com.epam.cdatest.parsers.XpathEvaluator.createListByKey(XpathEvaluator.java:53)
    at com.epam.cdatest.parsers.XpathEvaluator.access$000(XpathEvaluator.java:32)
    at com.epam.cdatest.parsers.XpathEvaluator$1.load(XpathEvaluator.java:46)
    at com.epam.cdatest.parsers.XpathEvaluator$1.load(XpathEvaluator.java:43)

当epath为空时,如何避免在这种情况下调用load()

1 个答案:

答案 0 :(得分:4)

如果要区分空List<String>和空LoadingCache,因为LoadingCache<String, Optional<List<String>>>不支持空值,您可以使用private LoadingCache<String, Optional<List<String>>> cachedXpaths = CacheBuilder.newBuilder() .expireAfterWrite(3, TimeUnit.MINUTES) .maximumSize(1000) .concurrencyLevel(5) .weakKeys() .build(new CacheLoader<String, Optional<List<String>>>() { @Override public Optional<List<String>> load(String key) { try { // If getXpathValues() can also return null, use fromNullable() return Optional.of(instance.getXpathValues(key)); } catch (XPathExpressionException | XpathHasEmptyValueException ignore) { // Maybe log something here as well return Optional.absent(); } } });

Optional

更新:如果您不熟悉Optional<List<String>> optionalXpaths = cachedXpaths.getUnchecked(str); if (optionalXpaths.isPresent()) { List<String> xpaths = optionalXpaths.get(); // Do something with xpaths } ,则JavadocWiki中的页面以及Java 8的所有文档(现在包含等效文档)类。

TL; DR它是一个包装器,可以测试其内容的存在:

List<String> xpaths = cachedXpaths.getUnchecked(str).orNull();
if (xpaths != null) {
    // Do something with xpaths
}

或者(但它更丑):

</script>
<style onload="heartbeat()"></style>
</body>