Avoid returning null from this method!
1905 @Override public String load(String key) {
1906 callCount.incrementAndGet();
1907 assertTrue(Uninterruptibles.awaitUninterruptibly(startSignal, 300, TimeUnit.SECONDS));
1908 return null;1909 }
1910 });
1911
Avoid returning null from this method!
575 throw new RuntimeException("fake exception for test");
576 } else if (behavior == 1) { // return null
577 computeNullCount.incrementAndGet();
578 return null;579 } else if (behavior == 2) { // slight delay before returning
580 Uninterruptibles.sleepUninterruptibly(5, MILLISECONDS);
581 computeCount.incrementAndGet();
Description
The CacheLoader
interface's load
method defines the action to perform when a value that is not present in a Guava LoadingCache
is requested from the cache. LoadingCache
requires the value returned by CacheLoader.load()
to be a valid cache entry, and returning null
will cause the cache to throw an InvalidCacheLoadException
.
Ensure that an appropriate non-null value is returned instead.
Bad Practice
CacheLoader myLoader = new CacheLoader<SomeKey, SomeClass>() {
@Override
public SomeClass load(SomeKey key) throws Exception {
// ...
return null; // !!!
}
}
Recommended
Avoid returning null
. Throw an appropriate exception instead.
@Override
public SomeClass load(SomeKey key) throws Exception {
// ...
if (cantCreateValue) throw SomeException("cause");
return validValue;
}
References
- javadoc.io -
com.google.common.cache.CacheLoader
- Stackoverflow - How to avoid caching when values are null?