本文介绍了使用Guava MapMaker / CacheBuilder处理空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用MapMaker / CacheBuilder创建缓存,但我不明白如何正确处理空值。

I try to make a cache using MapMaker/CacheBuilder but I don't understand how to properly handle null values.

 ConcurrentMap<Key, Graph> graphs = new MapMaker()
       .concurrencyLevel(4)
       .weakKeys()
       .maximumSize(10000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .makeComputingMap(
           new Function<Key, Graph>() {
             public Graph apply(Key key) {
               return createExpensiveGraph(key);
             }
           });

如果方法createExpensiveGraph返回空值,则抛出NullpointerException。
我不明白为什么ComputingConcurrentHashMap会抛出一个NPE而不是只返回一个空值。

If the method createExpensiveGraph returns a null value, then a NullpointerException is thrown.I don't understand why the ComputingConcurrentHashMap throws a NPE instead of just returning a null value.

如何正确处理这个?只是捕获NPE并返回null?
我错过了什么吗?

How to properly handle this ? Just catch the NPE and return null instead ?Am I missing something ?

推荐答案

Guava试图强迫你避免使用 null 尽可能,因为存在 null 时的不正确或无证件行为会导致大量混淆和错误。我认为尽可能避免使用空值绝对是一个好主意,如果你可以修改你的代码使它不使用 null ,我强烈推荐这种方法。

Guava tries to force you to avoid using null wherever possible, because improper or undocumented behavior in the presence of null can cause a huge amount of confusion and bugs. I think it's definitely a good idea to avoid using nulls wherever possible, and if you can modify your code so that it doesn't use null, I strongly recommend that approach instead.

您的问题的答案关键取决于null值在您的应用程序中的实际含义。最有可能的是,这意味着这个密钥没有价值,或没有任何东西。在这种情况下,最好的办法是使用,用包装非空值>可选 .of并使用 Optional.absent()而不是 null 。如果必须将其转换为null或非null值,则可以使用 Optional.orNull()

The answer to your question critically depends on what a "null" value actually means in your application. Most likely, it means that there's "no value" for this key, or "nothing there." In this case, probably your best bet is to use Optional, wrapping non-null values with Optional.of and using Optional.absent() instead of null. If you must turn that into a null or non-null value, you can use Optional.orNull().

这篇关于使用Guava MapMaker / CacheBuilder处理空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:59