Cache#computeIfAbsent should throw if loader returns null value

This commit is contained in:
Jason Tedor 2015-10-08 12:19:51 -04:00
parent 02a7d9a565
commit 8d33be83b7
2 changed files with 15 additions and 2 deletions

View File

@ -307,9 +307,10 @@ public class Cache<K, V> {
} catch (Exception e) {
throw new ExecutionException(e);
}
if (value != null) {
put(key, value, now);
if (value == null) {
throw new ExecutionException(new NullPointerException("loader returned a null value"));
}
put(key, value, now);
}
}
}

View File

@ -29,6 +29,8 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReferenceArray;
import static org.hamcrest.CoreMatchers.instanceOf;
public class CacheTests extends ESTestCase {
private int numberOfEntries;
@ -491,6 +493,16 @@ public class CacheTests extends ESTestCase {
}
}
public void testComputeIfAbsentThrowsExceptionIfLoaderReturnsANullValue() {
final Cache<Integer, String> cache = CacheBuilder.<Integer, String>builder().build();
try {
cache.computeIfAbsent(1, k -> null);
fail("expected ExecutionException");
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(NullPointerException.class));
}
}
// test that the cache is not corrupted under lots of concurrent modifications, even hitting the same key
// here be dragons: this test did catch one subtle bug during development; do not remove lightly
public void testTorture() throws InterruptedException {