diff --git a/.github/workflows/qodana.yml b/.github/workflows/qodana.yml index 4312f16ad4..1fac0498b5 100644 --- a/.github/workflows/qodana.yml +++ b/.github/workflows/qodana.yml @@ -50,11 +50,3 @@ jobs: uses: github/codeql-action/upload-sarif@v2 with: sarif_file: ${{ runner.temp }}/qodana/results/qodana.sarif.json - - name: View Instructions - run: | - echo "Download and extract the report artifact" - echo "Start a http server" - echo "... python2 -m SimpleHTTPServer" - echo "... python3 -m http.server" - echo "The report is available at http://localhost:8000" - echo "For more details see https://www.jetbrains.com/help/qodana" diff --git a/caffeine/build.gradle b/caffeine/build.gradle index 68fd9c55b1..7f18b31ced 100644 --- a/caffeine/build.gradle +++ b/caffeine/build.gradle @@ -125,7 +125,6 @@ tasks.named('compileJava').configure { } tasks.named('compileTestJava').configure { dependsOn jar, compileCodeGenJava - options.errorprone.disable('CheckReturnValue') } tasks.named('sourcesJar').configure { dependsOn generateLocalCaches, generateNodes diff --git a/caffeine/src/jmh/java/com/github/benmanes/caffeine/cache/impl/ConcurrentHashMapV7.java b/caffeine/src/jmh/java/com/github/benmanes/caffeine/cache/impl/ConcurrentHashMapV7.java index e0ce547e8a..96f96d0c56 100644 --- a/caffeine/src/jmh/java/com/github/benmanes/caffeine/cache/impl/ConcurrentHashMapV7.java +++ b/caffeine/src/jmh/java/com/github/benmanes/caffeine/cache/impl/ConcurrentHashMapV7.java @@ -113,7 +113,7 @@ * @param the type of keys maintained by this map * @param the type of mapped values */ -@SuppressWarnings({"all", "deprecation", "CheckReturnValue", "JdkObsolete", "rawtypes", "serial", +@SuppressWarnings({"all", "CheckReturnValue", "deprecation", "JdkObsolete", "rawtypes", "serial", "unchecked", "UnnecessaryParentheses", "UnusedNestedClass", "UnusedVariable", "YodaCondition"}) public class ConcurrentHashMapV7 extends AbstractMap implements ConcurrentMap, Serializable { diff --git a/caffeine/src/jmh/java/com/github/benmanes/caffeine/profiler/ProfilerHook.java b/caffeine/src/jmh/java/com/github/benmanes/caffeine/profiler/ProfilerHook.java index e9d64345f4..72a15dc99b 100644 --- a/caffeine/src/jmh/java/com/github/benmanes/caffeine/profiler/ProfilerHook.java +++ b/caffeine/src/jmh/java/com/github/benmanes/caffeine/profiler/ProfilerHook.java @@ -39,7 +39,6 @@ public abstract class ProfilerHook { calls = new LongAdder(); } - @SuppressWarnings("CheckReturnValue") public final void run() { scheduleStatusTask(); ConcurrentTestHarness.timeTasks(NUM_THREADS, this::profile); diff --git a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java index 1d311c1258..708cac1722 100644 --- a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java +++ b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java @@ -2220,8 +2220,8 @@ public boolean containsValue(Object value) { @Override public Map getAllPresent(Iterable keys) { - var result = new LinkedHashMap(calculateHashMapCapacity(keys)); - for (Object key : keys) { + var result = new LinkedHashMap(calculateHashMapCapacity(keys)); + for (K key : keys) { result.put(key, null); } @@ -2235,9 +2235,7 @@ public Map getAllPresent(Iterable keys) { iter.remove(); } else { if (!isComputingAsync(node)) { - @SuppressWarnings("unchecked") - K castedKey = (K) entry.getKey(); - tryExpireAfterRead(node, castedKey, value, expiry(), now); + tryExpireAfterRead(node, entry.getKey(), value, expiry(), now); setAccessTime(node, now); } V refreshed = afterRead(node, now, /* recordHit */ false); @@ -2247,9 +2245,7 @@ public Map getAllPresent(Iterable keys) { statsCounter().recordHits(result.size()); statsCounter().recordMisses(uniqueKeys - result.size()); - @SuppressWarnings("unchecked") - Map castedResult = (Map) result; - return Collections.unmodifiableMap(castedResult); + return Collections.unmodifiableMap(result); } @Override diff --git a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/LocalAsyncCache.java b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/LocalAsyncCache.java index 1076ef338f..6cafaaaa6d 100644 --- a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/LocalAsyncCache.java +++ b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/LocalAsyncCache.java @@ -486,17 +486,17 @@ abstract class AbstractCacheView implements Cache, Serializable { @Override public Map getAllPresent(Iterable keys) { - var result = new LinkedHashMap(calculateHashMapCapacity(keys)); - for (Object key : keys) { + var result = new LinkedHashMap(calculateHashMapCapacity(keys)); + for (K key : keys) { result.put(key, null); } int uniqueKeys = result.size(); for (var iter = result.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = iter.next(); + Map.Entry entry = iter.next(); CompletableFuture future = asyncCache().cache().get(entry.getKey()); - Object value = Async.getIfReady(future); + V value = Async.getIfReady(future); if (value == null) { iter.remove(); } else { @@ -506,9 +506,7 @@ public Map getAllPresent(Iterable keys) { asyncCache().cache().statsCounter().recordHits(result.size()); asyncCache().cache().statsCounter().recordMisses(uniqueKeys - result.size()); - @SuppressWarnings("unchecked") - var castedResult = (Map) result; - return Collections.unmodifiableMap(castedResult); + return Collections.unmodifiableMap(result); } @Override diff --git a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/SnapshotEntry.java b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/SnapshotEntry.java index b05e60f619..edf01f3ede 100644 --- a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/SnapshotEntry.java +++ b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/SnapshotEntry.java @@ -82,10 +82,13 @@ public static SnapshotEntry forEntry(K key, V value) { public static SnapshotEntry forEntry(K key, V value, long snapshot, int weight, long expiresAt, long refreshableAt) { long unsetTicks = snapshot + Long.MAX_VALUE; - int features = 0 - | ((refreshableAt == unsetTicks) ? 0b000 : 0b100) - | ((expiresAt == unsetTicks) ? 0b000 : 0b010) - | ((weight < 0) || (weight == 1) ? 0b000 : 0b001); + boolean refresh = (refreshableAt == unsetTicks); + boolean weights = (weight < 0) || (weight == 1); + boolean expires = (expiresAt == unsetTicks); + int features = + (refresh ? 0b000 : 0b100) + | (expires ? 0b000 : 0b010) + | (weights ? 0b000 : 0b001); switch (features) { // optimized for common cases case 0b000: return new SnapshotEntry<>(key, value, snapshot); case 0b001: return new WeightedEntry<>(key, value, snapshot, weight); diff --git a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/UnboundedLocalCache.java b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/UnboundedLocalCache.java index 94e2ab9d45..ccd497ddee 100644 --- a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/UnboundedLocalCache.java +++ b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/UnboundedLocalCache.java @@ -145,15 +145,15 @@ public long estimatedSize() { @Override public Map getAllPresent(Iterable keys) { - var result = new LinkedHashMap(calculateHashMapCapacity(keys)); - for (Object key : keys) { + var result = new LinkedHashMap(calculateHashMapCapacity(keys)); + for (K key : keys) { result.put(key, null); } int uniqueKeys = result.size(); for (var iter = result.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = iter.next(); - Object value = data.get(entry.getKey()); + Map.Entry entry = iter.next(); + V value = data.get(entry.getKey()); if (value == null) { iter.remove(); } else { @@ -163,9 +163,7 @@ public Map getAllPresent(Iterable keys) { statsCounter.recordHits(result.size()); statsCounter.recordMisses(uniqueKeys - result.size()); - @SuppressWarnings("unchecked") - var castedResult = (Map) result; - return Collections.unmodifiableMap(castedResult); + return Collections.unmodifiableMap(result); } @Override diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java index 3e6fda492b..716ba10271 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java @@ -81,6 +81,7 @@ public final class AsyncCacheTest { /* --------------- getIfPresent --------------- */ + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getIfPresent_nullKey(AsyncCache cache, CacheContext context) { @@ -107,18 +108,21 @@ public void getIfPresent_present(AsyncCache cache, CacheContext contex /* --------------- getFunc --------------- */ @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getFunc_nullKey(AsyncCache cache, CacheContext context) { cache.get(null, key -> null); } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getFunc_nullLoader(AsyncCache cache, CacheContext context) { cache.get(context.absentKey(), (Function) null); } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getFunc_nullKeyAndLoader(AsyncCache cache, CacheContext context) { cache.get(null, (Function) null); @@ -227,12 +231,14 @@ public void getFunc_present(AsyncCache cache, CacheContext context) { /* --------------- getBiFunc --------------- */ @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getBiFunc_nullKey(AsyncCache cache, CacheContext context) { cache.get(null, (key, executor) -> CompletableFuture.completedFuture(null)); } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getBiFunc_nullLoader(AsyncCache cache, CacheContext context) { BiFunction> mappingFunction = null; @@ -240,6 +246,7 @@ public void getBiFunc_nullLoader(AsyncCache cache, CacheContext contex } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getBiFunc_nullKeyAndLoader(AsyncCache cache, CacheContext context) { BiFunction> mappingFunction = null; @@ -247,6 +254,7 @@ public void getBiFunc_nullKeyAndLoader(AsyncCache cache, CacheContext } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getBiFunc_throwsException(AsyncCache cache, CacheContext context) { try { @@ -258,6 +266,7 @@ public void getBiFunc_throwsException(AsyncCache cache, CacheContext c } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) public void getBiFunc_throwsError(AsyncCache cache, CacheContext context) { try { @@ -269,6 +278,7 @@ public void getBiFunc_throwsError(AsyncCache cache, CacheContext conte } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getBiFunc_absent_null(AsyncCache cache, CacheContext context) { cache.get(context.absentKey(), (k, executor) -> null); @@ -304,6 +314,7 @@ public void getBiFunc_absent_failure_after(AsyncCache cache, CacheCont @CacheSpec @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") public void getBiFunc_absent_cancelled(AsyncCache cache, CacheContext context) { var cancelledFuture = new CompletableFuture(); cache.get(context.absentKey(), (k, executor) -> cancelledFuture); @@ -339,6 +350,7 @@ public void getBiFunc_present(AsyncCache cache, CacheContext context) /* --------------- getAllFunc --------------- */ @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullKeys(AsyncCache cache, CacheContext context) { @@ -346,6 +358,7 @@ public void getAllFunction_nullKeys(AsyncCache cache, CacheContext con } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullKeys_nullFunction( @@ -354,6 +367,7 @@ public void getAllFunction_nullKeys_nullFunction( } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullFunction(AsyncCache cache, CacheContext context) { @@ -361,6 +375,7 @@ public void getAllFunction_nullFunction(AsyncCache cache, CacheContext } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullKey(AsyncCache cache, CacheContext context) { @@ -564,6 +579,7 @@ public void getAllFunction_badLoader(AsyncCache cache, CacheContext co /* --------------- getAllBiFunc --------------- */ @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullKeys(AsyncCache cache, CacheContext context) { @@ -571,6 +587,7 @@ public void getAllBifunction_nullKeys(AsyncCache cache, CacheContext c } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullKeys_nullBifunction( @@ -580,6 +597,7 @@ public void getAllBifunction_nullKeys_nullBifunction( } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullBifunction(AsyncCache cache, CacheContext context) { @@ -588,6 +606,7 @@ public void getAllBifunction_nullBifunction(AsyncCache cache, CacheCon } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullKey(AsyncCache cache, CacheContext context) { @@ -615,6 +634,7 @@ public void getAllBiFunction_nullLookup(AsyncCache cache, CacheContext } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAllBifunction_immutable_keys(AsyncCache cache, CacheContext context) { cache.getAll(context.absentKeys(), (keys, executor) -> { @@ -642,6 +662,7 @@ public void getAllBifunction_absent_null(AsyncCache cache, CacheContex } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAllBifunction_absent_nullValue(AsyncCache cache, CacheContext context) { cache.getAll(context.absentKeys(), (keys, executor) -> null); @@ -658,6 +679,7 @@ public void getAllBifunction_absent_failure(AsyncCache cache, CacheCon } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getAllBifunction_absent_throwsException( AsyncCache cache, CacheContext context) { @@ -672,6 +694,7 @@ public void getAllBifunction_absent_throwsException( } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) public void getAllBifunction_absent_throwsError( AsyncCache cache, CacheContext context) { @@ -829,6 +852,7 @@ public void getAllBifunction_present_ordered_exceeds( } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_badLoader(AsyncCache cache, CacheContext context) { try { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java index e74c774439..726b9530e0 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java @@ -81,6 +81,7 @@ public final class AsyncLoadingCacheTest { /* --------------- get --------------- */ @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_null(AsyncLoadingCache cache, CacheContext context) { cache.get(null); @@ -164,16 +165,18 @@ public void get_present(AsyncLoadingCache cache, CacheContext context) /* --------------- getAll --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_null(AsyncLoadingCache cache, CacheContext context) { cache.getAll(null); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.NEGATIVE, Loader.BULK_NEGATIVE }, removalListener = { Listener.DISABLED, Listener.REJECTING }) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_nullKey(AsyncLoadingCache cache, CacheContext context) { cache.getAll(Collections.singletonList(null)); } @@ -195,6 +198,7 @@ public void getAll_immutable_keys_loader( .hasCauseThat().isInstanceOf(UnsupportedOperationException.class); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = Loader.ASYNC_BULK_MODIFY_KEYS) @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAll_immutable_keys_asyncLoader( @@ -261,6 +265,7 @@ public void getAll_absent_throwsCheckedException( } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.ASYNC_INTERRUPTED, Loader.ASYNC_BULK_INTERRUPTED }) public void getAll_absent_interrupted(AsyncLoadingCache cache, CacheContext context) { try { @@ -394,6 +399,7 @@ public void getAll_present_ordered_exceeds( } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(compute = Compute.ASYNC, removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAll_badLoader(CacheContext context) { var loader = new AsyncCacheLoader() { @@ -605,6 +611,7 @@ public void refresh_current_removed(CacheContext context) { /* --------------- AsyncCacheLoader --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = UnsupportedOperationException.class) public void asyncLoadAll() throws Exception { AsyncCacheLoader loader = (key, executor) -> key.negate().asFuture(); @@ -618,6 +625,7 @@ public void asyncReload() throws Exception { assertThat(future).succeedsWith(-1); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void bulk_function_null() { Function, Map> f = null; @@ -641,6 +649,7 @@ public void bulk_function_present() throws Exception { assertThat(loader.asyncLoad(Int.valueOf(1), Runnable::run)).succeedsWith(1); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void bulk_bifunction_null() { BiFunction, Executor, CompletableFuture>> f = null; diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java index d7601684d4..d0f1ed5ad2 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java @@ -39,6 +39,7 @@ public Object[][] buffer() { } @Test(dataProvider = "buffer") + @SuppressWarnings("CheckReturnValue") public void offer(BoundedBuffer buffer) { ConcurrentTestHarness.timeTasks(10, () -> { for (int i = 0; i < 100; i++) { @@ -50,6 +51,7 @@ public void offer(BoundedBuffer buffer) { } @Test(dataProvider = "buffer") + @SuppressWarnings("CheckReturnValue") public void drain(BoundedBuffer buffer) { for (int i = 0; i < BoundedBuffer.BUFFER_SIZE; i++) { buffer.offer(Boolean.TRUE); @@ -81,6 +83,7 @@ public void offerAndDrain(BoundedBuffer buffer) { } @Test + @SuppressWarnings("CheckReturnValue") public void overflow() { var buffer = new BoundedBuffer.RingBuffer(null); buffer.writeCounter = Long.MAX_VALUE; diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java index eb9cfbaae1..5f5b67d05a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java @@ -38,9 +38,11 @@ import static com.github.benmanes.caffeine.cache.testing.CacheSubject.assertThat; import static com.github.benmanes.caffeine.testing.Awaits.await; import static com.github.benmanes.caffeine.testing.FutureSubject.assertThat; +import static com.github.benmanes.caffeine.testing.IntSubject.assertThat; import static com.github.benmanes.caffeine.testing.MapSubject.assertThat; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth8.assertThat; import static java.lang.Thread.State.BLOCKED; import static java.lang.Thread.State.WAITING; import static java.util.Locale.US; @@ -273,10 +275,12 @@ public void rescheduleDrainBuffers() { .evictionListener(evictionListener) .maximumSize(0) .build()); - cache.put(Int.valueOf(1), Int.valueOf(1)); + var oldValue1 = cache.put(Int.valueOf(1), Int.valueOf(1)); + assertThat(oldValue1).isNull(); await().untilTrue(evicting); - cache.put(Int.valueOf(2), Int.valueOf(2)); + var oldValue2 = cache.put(Int.valueOf(2), Int.valueOf(2)); + assertThat(oldValue2).isAnyOf(Int.valueOf(1), null); assertThat(cache.drainStatus).isEqualTo(PROCESSING_TO_REQUIRED); done.set(true); @@ -290,13 +294,15 @@ public void rescheduleDrainBuffers() { removalListener = Listener.CONSUMING) public void scheduleDrainBuffers_rejected( BoundedLocalCache cache, CacheContext context) { - cache.put(context.absentKey(), context.absentValue()); + var oldValue = cache.put(context.absentKey(), context.absentValue()); + assertThat(oldValue).isNull(); assertThat(cache.drainStatus).isEqualTo(IDLE); assertThat(cache.writeBuffer.isEmpty()).isTrue(); assertThat(cache.evictionLock.isLocked()).isFalse(); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void shouldDrainBuffers_invalidDrainStatus() { var cache = new BoundedLocalCache( @@ -441,9 +447,10 @@ public void afterWrite_drainFullWriteBuffer( @CacheSpec(population = Population.EMPTY, executor = CacheExecutor.DISCARDING) public void afterWrite_drainFullWriteBuffer_discarded( BoundedLocalCache cache, CacheContext context) { - cache.put(context.absentKey(), context.absentValue()); + var oldValue = cache.put(context.absentKey(), context.absentValue()); assertThat(cache.drainStatus).isEqualTo(PROCESSING_TO_IDLE); assertThat(cache.evictionLock.isLocked()).isFalse(); + assertThat(oldValue).isNull(); int[] queued = { 1 }; Runnable pendingTask = () -> queued[0]++; @@ -490,7 +497,9 @@ public void afterWrite_exception() { public void weightedSize_maintenance(BoundedLocalCache cache, CacheContext context, Eviction eviction) { cache.drainStatus = REQUIRED; - eviction.weightedSize(); + var weight = eviction.weightedSize(); + + assertThat(weight).isPresent(); assertThat(cache.drainStatus).isEqualTo(IDLE); } @@ -499,7 +508,9 @@ public void weightedSize_maintenance(BoundedLocalCache cache, public void maximumSize_maintenance(BoundedLocalCache cache, CacheContext context, Eviction eviction) { cache.drainStatus = REQUIRED; - eviction.getMaximum(); + var maximum = eviction.getMaximum(); + + assertThat(maximum).isEqualTo(context.maximumWeightOrSize()); assertThat(cache.drainStatus).isEqualTo(IDLE); } @@ -510,8 +521,9 @@ public void maximumSize_maintenance(BoundedLocalCache cache, public void overflow_add_one(BoundedLocalCache cache, CacheContext context) { long actualWeight = cache.weightedSize(); cache.setWeightedSize(BoundedLocalCache.MAXIMUM_CAPACITY); - cache.put(context.absentKey(), context.absentValue()); + var oldValue = cache.put(context.absentKey(), context.absentValue()); + assertThat(oldValue).isNull(); assertThat(cache).hasSize(context.initialSize()); assertThat(cache.weightedSize()).isEqualTo(BoundedLocalCache.MAXIMUM_CAPACITY); @@ -556,9 +568,10 @@ public void overflow_add_many(BoundedLocalCache cache, CacheContext co maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.VALUE) public void overflow_update_one(BoundedLocalCache cache, CacheContext context) { cache.setWeightedSize(BoundedLocalCache.MAXIMUM_CAPACITY); - cache.put(context.firstKey(), Int.MAX_VALUE); + var oldValue = cache.put(context.firstKey(), Int.MAX_VALUE); assertThat(cache).hasSizeLessThan(1 + context.initialSize()); + assertThat(oldValue).isEqualTo(context.original().get(context.firstKey())); assertThat(cache.weightedSize()).isAtMost(BoundedLocalCache.MAXIMUM_CAPACITY); var removed = new HashMap<>(context.original()); @@ -604,16 +617,19 @@ public void overflow_update_many(BoundedLocalCache cache, CacheContext public void evict_alreadyRemoved(BoundedLocalCache cache, CacheContext context) { var oldEntry = Iterables.get(context.absent().entrySet(), 0); var newEntry = Iterables.get(context.absent().entrySet(), 1); + var oldValue = cache.put(oldEntry.getKey(), oldEntry.getValue()); + assertThat(oldValue).isNull(); var removed = new AtomicBoolean(); - cache.put(oldEntry.getKey(), oldEntry.getValue()); cache.evictionLock.lock(); try { var lookupKey = cache.nodeFactory.newLookupKey(oldEntry.getKey()); var node = cache.data.get(lookupKey); checkStatus(node, Status.ALIVE); ConcurrentTestHarness.execute(() -> { - cache.put(newEntry.getKey(), newEntry.getValue()); + var value = cache.put(newEntry.getKey(), newEntry.getValue()); + assertThat(value).isNull(); + assertThat(cache.remove(oldEntry.getKey())).isEqualTo(oldEntry.getValue()); removed.set(true); }); @@ -681,7 +697,10 @@ public void evict_wtinylfu(Cache cache, CacheContext context) { } private void checkReorder(Cache cache, List keys, List expect) { - keys.forEach(cache::getIfPresent); + for (var key : keys) { + var value = cache.getIfPresent(key); + assertThat(value).isNotNull(); + } checkContainsInOrder(cache, expect); } @@ -704,13 +723,15 @@ public void evict_candidate_lru(BoundedLocalCache cache, CacheContext cache.setMainProtectedMaximum(0); cache.setWindowMaximum(context.maximumSize()); for (int i = 0; i < context.maximumSize(); i++) { - cache.put(Int.valueOf(i), Int.valueOf(i)); + var oldValue = cache.put(Int.valueOf(i), Int.valueOf(i)); + assertThat(oldValue).isNull(); } var expected = cache.accessOrderWindowDeque().stream() .map(Node::getKey).collect(toImmutableList()); cache.setWindowMaximum(0L); - cache.evictFromWindow(); + var candidate = cache.evictFromWindow(); + assertThat(candidate).isNotNull(); var actual = cache.accessOrderProbationDeque().stream() .map(Node::getKey).collect(toImmutableList()); @@ -723,7 +744,8 @@ public void evict_candidate_lru(BoundedLocalCache cache, CacheContext removalListener = Listener.CONSUMING) public void evict_victim_lru(BoundedLocalCache cache, CacheContext context) { cache.setWindowMaximum(0); - cache.evictFromWindow(); + var candidate = cache.evictFromWindow(); + assertThat(candidate).isNotNull(); var expected = FluentIterable .from(cache.accessOrderProbationDeque()) @@ -746,7 +768,8 @@ public void evict_window_candidates(BoundedLocalCache cache, CacheCont cache.setMainProtectedMaximum(0); for (int i = 0; i < context.maximumSize(); i++) { - cache.put(Int.valueOf(i), Int.valueOf(i)); + var value = cache.put(Int.valueOf(i), Int.valueOf(i)); + assertThat(value).isNull(); } Arrays.fill(cache.frequencySketch().table, 0L); @@ -770,7 +793,8 @@ public void evict_window_fallback(BoundedLocalCache cache, CacheContex cache.setMainProtectedMaximum(0); for (int i = 0; i < context.maximumSize(); i++) { - cache.put(Int.valueOf(i), Int.valueOf(i)); + var value = cache.put(Int.valueOf(i), Int.valueOf(i)); + assertThat(value).isNull(); } Arrays.fill(cache.frequencySketch().table, 0L); @@ -793,11 +817,12 @@ public void evict_candidateIsVictim(BoundedLocalCache cache, CacheCont cache.setWindowMaximum(context.maximumSize() / 2); for (int i = 0; i < context.maximumSize(); i++) { - cache.put(Int.valueOf(i), Int.valueOf(i)); + var value = cache.put(Int.valueOf(i), Int.valueOf(i)); + assertThat(value).isNull(); } while (!cache.accessOrderProbationDeque().isEmpty()) { var node = cache.accessOrderProbationDeque().removeFirst(); - cache.accessOrderProtectedDeque().offerLast(node); + cache.accessOrderProtectedDeque().addLast(node); node.makeMainProtected(); } Arrays.fill(cache.frequencySketch().table, 0L); @@ -824,7 +849,8 @@ public void evict_candidateIsVictim(BoundedLocalCache cache, CacheCont removalListener = Listener.CONSUMING) public void evict_toZero(BoundedLocalCache cache, CacheContext context) { for (int i = 0; i < context.maximumSize(); i++) { - cache.put(Int.valueOf(i), Int.valueOf(i)); + var value = cache.put(Int.valueOf(i), Int.valueOf(i)); + assertThat(value).isNull(); } Arrays.fill(cache.frequencySketch().table, 0L); @@ -850,7 +876,10 @@ public void evict_retired_candidate(BoundedLocalCache cache, CacheCont var expected = cache.accessOrderWindowDeque().peekFirst(); var key = expected.getKey(); - ConcurrentTestHarness.execute(() -> cache.remove(key)); + ConcurrentTestHarness.execute(() -> { + var value = cache.remove(key); + assertThat(value).isNotNull(); + }); await().until(() -> !cache.containsKey(key)); assertThat(expected.isRetired()).isTrue(); @@ -874,7 +903,10 @@ public void evict_retired_victim(BoundedLocalCache cache, CacheContext var expected = cache.accessOrderProbationDeque().peekFirst(); var key = expected.getKey(); - ConcurrentTestHarness.execute(() -> cache.remove(key)); + ConcurrentTestHarness.execute(() -> { + var value = cache.remove(key); + assertThat(value).isNotNull(); + }); await().until(() -> !cache.containsKey(key)); assertThat(expected.isRetired()).isTrue(); @@ -894,11 +926,18 @@ public void evict_retired_victim(BoundedLocalCache cache, CacheContext maximumSize = Maximum.FULL, weigher = CacheWeigher.VALUE) public void evict_zeroWeight(BoundedLocalCache cache, CacheContext context) { for (int i = 0; i < context.maximumSize(); i++) { - cache.put(Int.valueOf(i), Int.valueOf(1)); - cache.get(Int.valueOf(i - 1)); + var oldValue = intern(cache.put(Int.valueOf(i), Int.valueOf(1))); + assertThat(oldValue).isNull(); + + var value = cache.get(Int.valueOf(i - 1)); + assertThat(value).isAnyOf(Int.valueOf(1), null); } - cache.put(cache.accessOrderWindowDeque().peekFirst().getKey(), Int.valueOf(0)); - cache.put(cache.accessOrderProbationDeque().peekFirst().getKey(), Int.valueOf(0)); + + var window = cache.put(cache.accessOrderWindowDeque().peekFirst().getKey(), Int.valueOf(0)); + assertThat(window).isNotNull(); + + var main = cache.put(cache.accessOrderProbationDeque().peekFirst().getKey(), Int.valueOf(0)); + assertThat(main).isNotNull(); cache.setMaximumSize(0); cache.evictEntries(); @@ -973,7 +1012,7 @@ public void evict_update() { started.set(true); ConcurrentTestHarness.execute(() -> { - localCache.compute(key, (k, v) -> { + var value = localCache.compute(key, (k, v) -> { if (started.get()) { writing.set(true); await().untilAsserted(() -> assertThat(evictor.getState()).isEqualTo(BLOCKED)); @@ -981,11 +1020,13 @@ public void evict_update() { previousValue.set(v); return newValue; }); + assertThat(value).isEqualTo(newValue); }); await().untilTrue(writing); var node = localCache.data.values().iterator().next(); - localCache.evictEntry(node, RemovalCause.SIZE, 0); + var evicted = localCache.evictEntry(node, SIZE, 0); + assertThat(evicted).isTrue(); await().untilAtomic(evictedValue, is(newValue)); await().untilAtomic(previousValue, is(oldValue)); @@ -998,12 +1039,12 @@ public void evict_update() { initialCapacity = InitialCapacity.EXCESSIVE, removalListener = Listener.CONSUMING) public void evict_update_entryTooBig_window( BoundedLocalCache cache, CacheContext context) { - cache.put(Int.valueOf(9), Int.valueOf(9)); - cache.put(Int.valueOf(1), Int.valueOf(1)); + cache.putAll(Map.of(Int.valueOf(9), Int.valueOf(9), Int.valueOf(1), Int.valueOf(1))); var lookupKey = cache.nodeFactory.newLookupKey(Int.valueOf(1)); assertThat(cache.data.get(lookupKey).inWindow()).isTrue(); - cache.put(Int.valueOf(1), Int.valueOf(20)); + var oldValue = cache.put(Int.valueOf(1), Int.valueOf(20)); + assertThat(oldValue).isEqualTo(1); assertThat(cache.weightedSize()).isAtMost(context.maximumSize()); assertThat(context).removalNotifications().withCause(REPLACED) @@ -1022,12 +1063,14 @@ public void evict_update_entryTooBig_window( public void evict_update_entryTooBig_probation( BoundedLocalCache cache, CacheContext context) { for (int i = 1; i <= 10; i++) { - cache.put(Int.valueOf(i), Int.valueOf(1)); + var oldValue = cache.put(Int.valueOf(i), Int.valueOf(1)); + assertThat(oldValue).isNull(); } var lookupKey = cache.nodeFactory.newLookupKey(Int.valueOf(1)); assertThat(cache.data.get(lookupKey).inMainProbation()).isTrue(); - cache.put(Int.valueOf(1), Int.valueOf(20)); + var oldValue = cache.put(Int.valueOf(1), Int.valueOf(20)); + assertThat(oldValue).isEqualTo(1); assertThat(cache.weightedSize()).isAtMost(context.maximumSize()); assertThat(context).removalNotifications().withCause(REPLACED) @@ -1046,14 +1089,18 @@ public void evict_update_entryTooBig_probation( public void evict_update_entryTooBig_protected( BoundedLocalCache cache, CacheContext context) { for (int i = 1; i <= 10; i++) { - cache.put(Int.valueOf(i), Int.valueOf(1)); - cache.get(Int.valueOf(1)); + var oldValue = cache.put(Int.valueOf(i), Int.valueOf(1)); + assertThat(oldValue).isNull(); + + var value = cache.get(Int.valueOf(1)); + assertThat(value).isEqualTo(1); } cache.cleanUp(); var lookupKey = cache.nodeFactory.newLookupKey(Int.valueOf(1)); assertThat(cache.data.get(lookupKey).inMainProtected()).isTrue(); - cache.put(Int.valueOf(1), Int.valueOf(20)); + var oldValue = cache.put(Int.valueOf(1), Int.valueOf(20)); + assertThat(oldValue).isEqualTo(1); assertThat(cache.weightedSize()).isAtMost(context.maximumSize()); assertThat(context).removalNotifications().withCause(REPLACED) @@ -1073,7 +1120,9 @@ public void evict_resurrect_collected(BoundedLocalCache cache, CacheCo Int oldValue = Int.valueOf(2); Int newValue = Int.valueOf(3); - cache.put(key, oldValue); + var initialValue = cache.put(key, oldValue); + assertThat(initialValue).isNull(); + var node = cache.data.get(cache.referenceKey(key)); @SuppressWarnings("unchecked") var ref = (Reference) node.getValueReference(); @@ -1082,7 +1131,7 @@ public void evict_resurrect_collected(BoundedLocalCache cache, CacheCo var started = new AtomicBoolean(); var done = new AtomicBoolean(); var evictor = new AtomicReference(); - cache.compute(key, (k, v) -> { + var computed = cache.compute(key, (k, v) -> { assertThat(v).isNull(); ConcurrentTestHarness.execute(() -> { evictor.set(Thread.currentThread()); @@ -1096,6 +1145,7 @@ public void evict_resurrect_collected(BoundedLocalCache cache, CacheCo return newValue; }); + assertThat(computed).isEqualTo(newValue); await().untilTrue(done); assertThat(node.getValue()).isEqualTo(newValue); @@ -1269,12 +1319,13 @@ public void evict_resurrect_expireAfterWrite_entry(Cache cache, CacheC public void evict_resurrect_expireAfterVar( BoundedLocalCache cache, CacheContext context) { Int key = Int.valueOf(1); - cache.put(key, key); - var node = cache.data.get(cache.referenceKey(key)); + var oldValue = cache.put(key, key); + assertThat(oldValue).isNull(); var started = new AtomicBoolean(); var done = new AtomicBoolean(); var evictor = new AtomicReference(); + var node = cache.data.get(cache.referenceKey(key)); synchronized (node) { context.ticker().advance(Duration.ofHours(1)); ConcurrentTestHarness.execute(() -> { @@ -1307,7 +1358,9 @@ public void evict_collected_candidate(BoundedLocalCache cache, CacheCo var keyReference = (WeakKeyReference) candidate.getKeyReference(); keyReference.clear(); - cache.put(context.absentKey(), context.absentValue()); + var oldValue = cache.put(context.absentKey(), context.absentValue()); + assertThat(oldValue).isNull(); + assertThat(context).notifications().withCause(COLLECTED) .contains(null, value).exclusively(); } @@ -1335,28 +1388,40 @@ public void evict_collected_victim(BoundedLocalCache cache, CacheConte @CacheSpec(compute = Compute.SYNC, population = Population.FULL, maximumSize = Maximum.FULL) public void updateRecency_onGet(BoundedLocalCache cache, CacheContext context) { var first = firstBeforeAccess(cache, context); - updateRecency(cache, context, () -> cache.get(first.getKey())); + updateRecency(cache, context, () -> { + var value = cache.get(first.getKey()); + assertThat(value).isNotNull(); + }); } @Test(dataProvider = "caches") @CacheSpec(compute = Compute.SYNC, population = Population.FULL, maximumSize = Maximum.FULL) public void updateRecency_onPutIfAbsent(BoundedLocalCache cache, CacheContext context) { var first = firstBeforeAccess(cache, context); - updateRecency(cache, context, () -> cache.putIfAbsent(first.getKey(), first.getKey())); + updateRecency(cache, context, () -> { + var oldValue = cache.putIfAbsent(first.getKey(), first.getKey()); + assertThat(oldValue).isNotNull(); + }); } @Test(dataProvider = "caches") @CacheSpec(compute = Compute.SYNC, population = Population.FULL, maximumSize = Maximum.FULL) public void updateRecency_onPut(BoundedLocalCache cache, CacheContext context) { var first = firstBeforeAccess(cache, context); - updateRecency(cache, context, () -> cache.put(first.getKey(), first.getKey())); + updateRecency(cache, context, () -> { + var oldValue = cache.put(first.getKey(), first.getKey()); + assertThat(oldValue).isNotNull(); + }); } @Test(dataProvider = "caches") @CacheSpec(compute = Compute.SYNC, population = Population.FULL, maximumSize = Maximum.FULL) public void updateRecency_onReplace(BoundedLocalCache cache, CacheContext context) { var first = firstBeforeAccess(cache, context); - updateRecency(cache, context, () -> cache.replace(first.getKey(), first.getKey())); + updateRecency(cache, context, () -> { + var oldValue = cache.replace(first.getKey(), first.getKey()); + assertThat(oldValue).isNotNull(); + }); } @Test(dataProvider = "caches") @@ -1366,7 +1431,10 @@ public void updateRecency_onReplaceConditionally( var first = firstBeforeAccess(cache, context); Int value = first.getValue(); - updateRecency(cache, context, () -> cache.replace(first.getKey(), value, value)); + updateRecency(cache, context, () -> { + boolean replaced = cache.replace(first.getKey(), value, value); + assertThat(replaced).isTrue(); + }); } private static Node firstBeforeAccess( @@ -1402,12 +1470,17 @@ public void exceedsMaximumBufferSize_onRead( var buffer = cache.readBuffer; for (int i = 0; i < BoundedBuffer.BUFFER_SIZE; i++) { - buffer.offer(dummy); + var result = buffer.offer(dummy); + assertThat(result).isEqualTo(Buffer.SUCCESS); } - assertThat(buffer.offer(dummy)).isEqualTo(Buffer.FULL); + var result = buffer.offer(dummy); + assertThat(result).isEqualTo(Buffer.FULL); + + var refreshed = cache.afterRead(dummy, 0, /* recordHit */ true); + assertThat(refreshed).isNull(); - cache.afterRead(dummy, 0, /* recordHit */ true); - assertThat(buffer.offer(dummy)).isNotEqualTo(Buffer.FULL); + result = buffer.offer(dummy); + assertThat(result).isEqualTo(Buffer.SUCCESS); } @Test(dataProvider = "caches") @@ -1430,11 +1503,14 @@ public void fastpath(BoundedLocalCache cache, CacheContext context) { assertThat(cache.skipReadBuffer()).isTrue(); for (int i = 0; i < (context.maximumSize() / 2) - 1; i++) { - cache.put(Int.valueOf(i), Int.valueOf(-i)); + var oldValue = cache.put(Int.valueOf(i), Int.valueOf(-i)); + assertThat(oldValue).isNull(); } assertThat(cache.skipReadBuffer()).isTrue(); - cache.put(Int.valueOf(-1), Int.valueOf(-1)); + var oldValue = cache.put(Int.valueOf(-1), Int.valueOf(-1)); + assertThat(oldValue).isNull(); + assertThat(cache.skipReadBuffer()).isFalse(); assertThat(cache.get(Int.valueOf(0))).isNotNull(); assertThat(cache.readBuffer.writes()).isEqualTo(1); @@ -1448,22 +1524,27 @@ public void fastpath(BoundedLocalCache cache, CacheContext context) { public void drain_onRead(BoundedLocalCache cache, CacheContext context) { var buffer = cache.readBuffer; for (int i = 0; i < BoundedBuffer.BUFFER_SIZE; i++) { - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); } long pending = buffer.size(); assertThat(buffer.writes()).isEqualTo(pending); assertThat(pending).isEqualTo(BoundedBuffer.BUFFER_SIZE); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + assertThat(buffer.size()).isEqualTo(0); } @Test(dataProvider = "caches") @CacheSpec(compute = Compute.SYNC, population = Population.FULL, maximumSize = Maximum.FULL) public void drain_onRead_absent(BoundedLocalCache cache, CacheContext context) { + var value = cache.get(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + var buffer = cache.readBuffer; - cache.get(context.firstKey()); assertThat(buffer.size()).isEqualTo(1); assertThat(cache.get(context.absentKey())).isNull(); @@ -1477,7 +1558,8 @@ public void drain_onRead_absent(BoundedLocalCache cache, CacheContext @Test(dataProvider = "caches") @CacheSpec(compute = Compute.SYNC, population = Population.EMPTY, maximumSize = Maximum.FULL) public void drain_onWrite(BoundedLocalCache cache, CacheContext context) { - cache.put(Int.valueOf(1), Int.valueOf(1)); + var oldValue = cache.put(Int.valueOf(1), Int.valueOf(1)); + assertThat(oldValue).isNull(); int size = cache.accessOrderWindowDeque().size() + cache.accessOrderProbationDeque().size(); assertThat(cache.writeBuffer).isEmpty(); @@ -1512,7 +1594,10 @@ public void drain_blocksClear(BoundedLocalCache cache, CacheContext co @CacheSpec(compute = Compute.SYNC, population = Population.EMPTY, maximumSize = Maximum.FULL) public void drain_blocksOrderedMap(BoundedLocalCache cache, CacheContext context, Eviction eviction) { - checkDrainBlocks(cache, () -> eviction.coldest(((int) context.maximumSize()))); + checkDrainBlocks(cache, () -> { + var results = eviction.coldest(((int) context.maximumSize())); + assertThat(results).isEmpty(); + }); } @Test(dataProvider = "caches") @@ -1589,8 +1674,14 @@ private void prepareForAdaption(BoundedLocalCache cache, // Fill window and main spaces cache.clear(); cache.putAll(context.original()); - cache.keySet().forEach(cache::get); - cache.keySet().forEach(cache::get); + for (var key : cache.keySet()) { + var value = cache.get(key); + assertThat(value).isNotNull(); + } + for (var key : cache.keySet()) { + var value = cache.get(key); + assertThat(value).isNotNull(); + } } private void adapt(BoundedLocalCache cache, int sampleSize) { @@ -1600,7 +1691,10 @@ private void adapt(BoundedLocalCache cache, int sampleSize) { cache.climb(); // Fill main protected space - cache.keySet().forEach(cache::get); + for (var key : cache.keySet()) { + var value = cache.get(key); + assertThat(value).isNotNull(); + } } /* --------------- Expiration --------------- */ @@ -1613,11 +1707,13 @@ public void put_expireTolerance_expireAfterWrite( boolean mayCheckReads = context.isStrongKeys() && context.isStrongValues() && (cache.readBuffer != Buffer.>disabled()); - cache.put(Int.valueOf(1), Int.valueOf(1)); + var initialValue = cache.put(Int.valueOf(1), Int.valueOf(1)); + assertThat(initialValue).isNull(); assertThat(cache.writeBuffer.producerIndex).isEqualTo(2); // If within the tolerance, treat the update as a read - cache.put(Int.valueOf(1), Int.valueOf(2)); + var oldValue = cache.put(Int.valueOf(1), Int.valueOf(2)); + assertThat(oldValue).isEqualTo(1); if (mayCheckReads) { assertThat(cache.readBuffer.reads()).isEqualTo(0); assertThat(cache.readBuffer.writes()).isEqualTo(1); @@ -1626,7 +1722,8 @@ public void put_expireTolerance_expireAfterWrite( // If exceeds the tolerance, treat the update as a write context.ticker().advance(EXPIRE_WRITE_TOLERANCE + 1, TimeUnit.NANOSECONDS); - cache.put(Int.valueOf(1), Int.valueOf(3)); + var lastValue = cache.put(Int.valueOf(1), Int.valueOf(3)); + assertThat(lastValue).isEqualTo(2); if (mayCheckReads) { assertThat(cache.readBuffer.reads()).isEqualTo(1); assertThat(cache.readBuffer.writes()).isEqualTo(1); @@ -1638,18 +1735,21 @@ public void put_expireTolerance_expireAfterWrite( @CacheSpec(compute = Compute.SYNC, population = Population.EMPTY, expiry = CacheExpiry.MOCKITO, expiryTime = Expire.ONE_MINUTE) public void put_expireTolerance_expiry(BoundedLocalCache cache, CacheContext context) { - cache.put(Int.valueOf(1), Int.valueOf(1)); + var oldValue = cache.put(Int.valueOf(1), Int.valueOf(1)); + assertThat(oldValue).isNull(); assertThat(cache.writeBuffer.producerIndex).isEqualTo(2); // If within the tolerance, treat the update as a read - cache.put(Int.valueOf(1), Int.valueOf(2)); + oldValue = cache.put(Int.valueOf(1), Int.valueOf(2)); + assertThat(oldValue).isEqualTo(1); assertThat(cache.readBuffer.reads()).isEqualTo(0); assertThat(cache.readBuffer.writes()).isEqualTo(1); assertThat(cache.writeBuffer.producerIndex).isEqualTo(2); // If exceeds the tolerance, treat the update as a write context.ticker().advance(EXPIRE_WRITE_TOLERANCE + 1, TimeUnit.NANOSECONDS); - cache.put(Int.valueOf(1), Int.valueOf(3)); + oldValue = cache.put(Int.valueOf(1), Int.valueOf(3)); + assertThat(oldValue).isEqualTo(2); assertThat(cache.readBuffer.reads()).isEqualTo(1); assertThat(cache.readBuffer.writes()).isEqualTo(1); assertThat(cache.writeBuffer.producerIndex).isEqualTo(4); @@ -1657,7 +1757,8 @@ public void put_expireTolerance_expiry(BoundedLocalCache cache, CacheC // If the expiration time reduces by more than the tolerance, treat the update as a write when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) .thenReturn(Expire.ONE_MILLISECOND.timeNanos()); - cache.put(Int.valueOf(1), Int.valueOf(4)); + oldValue = cache.put(Int.valueOf(1), Int.valueOf(4)); + assertThat(oldValue).isEqualTo(3); assertThat(cache.readBuffer.reads()).isEqualTo(1); assertThat(cache.readBuffer.writes()).isEqualTo(1); assertThat(cache.writeBuffer.producerIndex).isEqualTo(6); @@ -1665,7 +1766,8 @@ public void put_expireTolerance_expiry(BoundedLocalCache cache, CacheC // If the expiration time increases by more than the tolerance, treat the update as a write when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) .thenReturn(Expire.FOREVER.timeNanos()); - cache.put(Int.valueOf(1), Int.valueOf(4)); + oldValue = cache.put(Int.valueOf(1), Int.valueOf(4)); + assertThat(oldValue).isEqualTo(4); assertThat(cache.readBuffer.reads()).isEqualTo(1); assertThat(cache.readBuffer.writes()).isEqualTo(1); assertThat(cache.writeBuffer.producerIndex).isEqualTo(8); @@ -1696,7 +1798,8 @@ public void put_warnIfEvictionBlocked(BoundedLocalCache cache, CacheCo if (done.get()) { return; } - cache.put(Int.valueOf(i), Int.valueOf(i)); + var oldValue = cache.put(Int.valueOf(i), Int.valueOf(i)); + assertThat(oldValue).isNull(); } }); @@ -1722,15 +1825,18 @@ public void put_warnIfEvictionBlocked(BoundedLocalCache cache, CacheCo @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void put_spinToCompute(BoundedLocalCache cache, CacheContext context) { - cache.put(context.absentKey(), context.absentValue()); + var initialValue = cache.put(context.absentKey(), context.absentValue()); + assertThat(initialValue).isNull(); + var node = cache.data.get(context.absentKey()); node.retire(); - cache.data.compute(context.absentKey(), (k, n) -> { + var value = cache.data.compute(context.absentKey(), (k, n) -> { var writer = new AtomicReference(); ConcurrentTestHarness.execute(() -> { writer.set(Thread.currentThread()); - cache.put(context.absentKey(), context.absentKey()); + var oldValue = cache.put(context.absentKey(), context.absentKey()); + assertThat(oldValue).isAnyOf(context.absentValue(), null); }); var threadState = EnumSet.of(BLOCKED, WAITING); @@ -1739,6 +1845,7 @@ public void put_spinToCompute(BoundedLocalCache cache, CacheContext co return null; }); + assertThat(value).isNull(); await().untilAsserted(() -> assertThat(cache).containsEntry(context.absentKey(), context.absentKey())); @@ -1790,7 +1897,8 @@ public void unschedule_cleanUp(BoundedLocalCache cache, CacheContext c doReturn(future).when(context.scheduler()).schedule(any(), any(), anyLong(), any()); for (int i = 0; i < 10; i++) { - cache.put(Int.valueOf(i), Int.valueOf(-i)); + var value = cache.put(Int.valueOf(i), Int.valueOf(-i)); + assertThat(value).isNull(); } assertThat(cache.pacer().nextFireTime).isNotEqualTo(0); assertThat(cache.pacer().future).isNotNull(); @@ -1815,7 +1923,8 @@ public void unschedule_invalidateAll(BoundedLocalCache cache, CacheCon doReturn(future).when(context.scheduler()).schedule(any(), any(), anyLong(), any()); for (int i = 0; i < 10; i++) { - cache.put(Int.valueOf(i), Int.valueOf(-i)); + var value = cache.put(Int.valueOf(i), Int.valueOf(-i)); + assertThat(value).isNull(); } assertThat(cache.pacer().nextFireTime).isNotEqualTo(0); assertThat(cache.pacer().future).isNotNull(); @@ -1834,7 +1943,9 @@ public void expirationDelay_window(BoundedLocalCache cache, CacheConte long stepSize = context.expireAfterAccess().timeNanos() / (2 * maximum); for (int i = 0; i < maximum; i++) { var key = CacheContext.intern(Int.valueOf(i)); - cache.put(key, key); + var value = cache.put(key, key); + assertThat(value).isNull(); + context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); } @@ -1846,7 +1957,8 @@ public void expirationDelay_window(BoundedLocalCache cache, CacheConte node.setAccessTime(context.ticker().read()); } for (var node : FluentIterable.from(cache.accessOrderProbationDeque()).skip(5).toList()) { - cache.get(node.getKey()); + var value = cache.get(node.getKey()); + assertThat(value).isEqualTo(node.getKey()); } context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); cache.cleanUp(); @@ -1864,7 +1976,9 @@ public void expirationDelay_probation(BoundedLocalCache cache, CacheCo long stepSize = context.expireAfterAccess().timeNanos() / (2 * context.maximumSize()); for (int i = 0; i < (int) context.maximumSize(); i++) { var key = CacheContext.intern(Int.valueOf(i)); - cache.put(key, key); + var value = cache.put(key, key); + assertThat(value).isNull(); + context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); } @@ -1875,7 +1989,8 @@ public void expirationDelay_probation(BoundedLocalCache cache, CacheCo node.setAccessTime(context.ticker().read()); } for (var node : FluentIterable.from(cache.accessOrderProbationDeque()).skip(5).toList()) { - cache.get(node.getKey()); + var value = cache.get(node.getKey()); + assertThat(value).isEqualTo(node.getKey()); } context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); cache.cleanUp(); @@ -1892,12 +2007,15 @@ public void expirationDelay_protected(BoundedLocalCache cache, CacheCo long stepSize = context.expireAfterAccess().timeNanos() / (2 * context.maximumSize()); for (int i = 0; i < (int) context.maximumSize(); i++) { var key = CacheContext.intern(Int.valueOf(i)); - cache.put(key, key); + var value = cache.put(key, key); + assertThat(value).isNull(); + context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); } for (var node : FluentIterable.from(cache.accessOrderProbationDeque()).skip(5).toList()) { - cache.get(node.getKey()); + var value = cache.get(node.getKey()); + assertThat(value).isEqualTo(node.getKey()); } context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); cache.cleanUp(); @@ -1921,11 +2039,14 @@ public void expirationDelay_writeOrder(BoundedLocalCache cache, CacheC long stepSize = context.expireAfterWrite().timeNanos() / (2 * context.maximumSize()); for (int i = 0; i < (int) context.maximumSize(); i++) { var key = CacheContext.intern(Int.valueOf(i)); - cache.put(key, key); + var value = cache.put(key, key); + assertThat(value).isNull(); + context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); } for (var key : cache.keySet()) { - cache.get(key); + var value = cache.get(key); + assertThat(value).isEqualTo(key); } cache.cleanUp(); @@ -1943,11 +2064,14 @@ public void expirationDelay_varTime(BoundedLocalCache cache, CacheCont long stepSize = context.expiryTime().timeNanos() / (2 * maximum); for (int i = 0; i < maximum; i++) { var key = CacheContext.intern(Int.valueOf(i)); - cache.put(key, key); + var value = cache.put(key, key); + assertThat(value).isNull(); + context.ticker().advance(stepSize, TimeUnit.NANOSECONDS); } for (var key : cache.keySet()) { - cache.get(key); + var value = cache.get(key); + assertThat(value).isEqualTo(key); } cache.cleanUp(); @@ -1980,13 +2104,15 @@ public void refreshIfNeeded_liveliness(CacheContext context) { })); // Seed the cache - cache.put(context.absentKey(), context.absentValue()); - var node = cache.data.get(context.absentKey()); + var oldValue = cache.put(context.absentKey(), context.absentValue()); + assertThat(oldValue).isNull(); // Remove the entry after the read, but before the refresh, and leave it as retired + var node = cache.data.get(context.absentKey()); doAnswer(invocation -> { ConcurrentTestHarness.execute(() -> { - cache.remove(context.absentKey()); + var value = cache.remove(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); }); await().until(() -> !cache.containsKey(context.absentKey())); assertThat(node.isRetired()).isTrue(); @@ -2035,13 +2161,17 @@ public CompletableFuture asyncReload(Int key, Int oldValue, Executor execut var refreshes = localCache.refreshes(); context.ticker().advance(2, TimeUnit.MINUTES); - ConcurrentTestHarness.execute(() -> cache.get(context.absentKey())); + ConcurrentTestHarness.execute(() -> { + var value = cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); + }); await().untilTrue(reloading); assertThat(node.getWriteTime() & 1L).isEqualTo(1); localCache.refreshes = null; - cache.get(context.absentKey()); + var value = cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); assertThat(localCache.refreshes).isNull(); refresh.set(true); @@ -2121,7 +2251,8 @@ public void refresh_startReloadBeforeLoadCompletion(CacheContext context) { public void brokenEquality_eviction(BoundedLocalCache cache, CacheContext context, Eviction eviction) { var key = new MutableInt(context.absentKey().intValue()); - cache.put(key, context.absentValue()); + var value = cache.put(key, context.absentValue()); + assertThat(value).isNull(); key.increment(); eviction.setMaximum(0); @@ -2146,7 +2277,8 @@ public void brokenEquality_eviction(BoundedLocalCache cache, public void brokenEquality_expiration( BoundedLocalCache cache, CacheContext context) { var key = new MutableInt(context.absentKey().intValue()); - cache.put(key, context.absentValue()); + var value = cache.put(key, context.absentValue()); + assertThat(value).isNull(); key.increment(); context.ticker().advance(1, TimeUnit.DAYS); @@ -2168,7 +2300,8 @@ public void brokenEquality_expiration( @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_clear(BoundedLocalCache cache, CacheContext context) { var key = new MutableInt(context.absentKey().intValue()); - cache.put(key, context.absentValue()); + var value = cache.put(key, context.absentValue()); + assertThat(value).isNull(); key.increment(); cache.clear(); @@ -2187,7 +2320,10 @@ public void brokenEquality_clear(BoundedLocalCache cache, CacheCont @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_put(BoundedLocalCache cache, CacheContext context) { - testForBrokenEquality(cache, context, key -> cache.put(key, context.absentValue())); + testForBrokenEquality(cache, context, key -> { + var value = cache.put(key, context.absentValue()); + assertThat(value).isEqualTo(context.absentValue()); + }); } @CheckMaxLogLevel(ERROR) @@ -2195,7 +2331,10 @@ public void brokenEquality_put(BoundedLocalCache cache, CacheCo @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_putIfAbsent( BoundedLocalCache cache, CacheContext context) { - testForBrokenEquality(cache, context, key -> cache.putIfAbsent(key, context.absentValue())); + testForBrokenEquality(cache, context, key -> { + var value = cache.putIfAbsent(key, context.absentValue()); + assertThat(value).isEqualTo(context.absentValue()); + }); } @CheckMaxLogLevel(ERROR) @@ -2203,7 +2342,10 @@ public void brokenEquality_putIfAbsent( @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_replace( BoundedLocalCache cache, CacheContext context) { - testForBrokenEquality(cache, context, key -> cache.replace(key, context.absentValue())); + testForBrokenEquality(cache, context, key -> { + var value = cache.replace(key, context.absentValue()); + assertThat(value).isEqualTo(context.absentValue()); + }); } @CheckMaxLogLevel(ERROR) @@ -2211,8 +2353,10 @@ public void brokenEquality_replace( @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_replaceConditionally( BoundedLocalCache cache, CacheContext context) { - testForBrokenEquality(cache, context, key -> - cache.replace(key, context.absentValue(), context.absentValue().negate())); + testForBrokenEquality(cache, context, key -> { + boolean replaced = cache.replace(key, context.absentValue(), context.absentValue().negate()); + assertThat(replaced).isTrue(); + }); } @CheckMaxLogLevel(ERROR) @@ -2220,7 +2364,10 @@ public void brokenEquality_replaceConditionally( @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_remove( BoundedLocalCache cache, CacheContext context) { - testForBrokenEquality(cache, context, cache::remove); + testForBrokenEquality(cache, context, key -> { + var value = cache.remove(key); + assertThat(value).isEqualTo(context.absentValue()); + }); } @CheckMaxLogLevel(ERROR) @@ -2228,13 +2375,17 @@ public void brokenEquality_remove( @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_removeConditionally( BoundedLocalCache cache, CacheContext context) { - testForBrokenEquality(cache, context, key -> cache.remove(key, context.absentValue())); + testForBrokenEquality(cache, context, key -> { + boolean removed = cache.remove(key, context.absentValue()); + assertThat(removed).isTrue(); + }); } private static void testForBrokenEquality(BoundedLocalCache cache, CacheContext context, Consumer task) { var key = new MutableInt(context.absentKey().intValue()); - cache.put(key, context.absentValue()); + var value = cache.put(key, context.absentValue()); + assertThat(value).isNull(); key.increment(); cache.clear(); @@ -2253,6 +2404,7 @@ private static void testForBrokenEquality(BoundedLocalCache cac /* --------------- Miscellaneous --------------- */ @Test + @SuppressWarnings("CheckReturnValue") public void cacheFactory_invalid() { try { LocalCacheFactory.loadFactory(/* builder */ null, /* loader */ null, @@ -2269,6 +2421,7 @@ public void cacheFactory_invalid() { } @Test + @SuppressWarnings("CheckReturnValue") public void nodeFactory_invalid() { try { NodeFactory.loadFactory(/* className */ null); @@ -2283,6 +2436,7 @@ public void nodeFactory_invalid() { } @Test + @SuppressWarnings("CheckReturnValue") public void unsupported() { var cache = Mockito.mock(BoundedLocalCache.class, InvocationOnMock::callRealMethod); @SuppressWarnings("MethodReferenceUsage") @@ -2317,10 +2471,11 @@ public void unsupported() { public void cleanupTask_ignore() { var task = new PerformCleanupTask(null); assertThat(task.getRawResult()).isNull(); + assertThat(task.cancel(false)).isFalse(); + assertThat(task.cancel(true)).isFalse(); task.completeExceptionally(null); task.setRawResult(null); task.complete(null); - task.cancel(true); } @Test(dataProviderClass = CacheProvider.class, dataProvider = "caches") @@ -2338,6 +2493,7 @@ public void node_string(BoundedLocalCache cache, CacheContext context) } @Test + @SuppressWarnings("CheckReturnValue") public void node_unsupported() { @SuppressWarnings("unchecked") Node node = Mockito.mock(Node.class, InvocationOnMock::callRealMethod); @@ -2368,7 +2524,7 @@ public void node_ignored() { } @Test - @SuppressWarnings("unchecked") + @SuppressWarnings({"CheckReturnValue", "unchecked"}) public void policy_unsupported() { Policy policy = Mockito.mock(Policy.class, InvocationOnMock::callRealMethod); var eviction = Mockito.mock(Eviction.class, InvocationOnMock::callRealMethod); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java index fe003f569e..48a16dc602 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java @@ -103,6 +103,7 @@ public void estimatedSize(Cache cache, CacheContext context) { /* --------------- getIfPresent --------------- */ @CheckNoStats + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getIfPresent_nullKey(Cache cache, CacheContext context) { @@ -130,6 +131,7 @@ public void getIfPresent_present(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_nullKey(Cache cache, CacheContext context) { cache.get(null, identity()); @@ -137,6 +139,7 @@ public void get_nullKey(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_nullLoader(Cache cache, CacheContext context) { cache.get(context.absentKey(), null); @@ -144,6 +147,7 @@ public void get_nullLoader(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_nullKeyAndLoader(Cache cache, CacheContext context) { cache.get(null, null); @@ -157,6 +161,7 @@ public void get_absent_null(Cache cache, CacheContext context) { } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void get_absent_throwsException(Cache cache, CacheContext context) { try { @@ -167,6 +172,7 @@ public void get_absent_throwsException(Cache cache, CacheContext conte } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) public void get_absent_throwsError(Cache cache, CacheContext context) { try { @@ -201,6 +207,7 @@ public void get_present(Cache cache, CacheContext context) { /* --------------- getAllPresent --------------- */ @CheckNoStats + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAllPresent_iterable_null(Cache cache, CacheContext context) { @@ -208,6 +215,7 @@ public void getAllPresent_iterable_null(Cache cache, CacheContext cont } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAllPresent_iterable_nullKey(Cache cache, CacheContext context) { @@ -324,12 +332,14 @@ class Key { /* --------------- getAll --------------- */ + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_null(Cache cache, CacheContext context) { cache.getAll(null, keys -> { throw new AssertionError(); }); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_nullKey(Cache cache, CacheContext context) { @@ -344,12 +354,14 @@ public void getAll_iterable_empty(Cache cache, CacheContext context) { assertThat(context).stats().hits(0).misses(0); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_function_null(Cache cache, CacheContext context) { cache.getAll(context.absentKeys(), null); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_function_nullValue(Cache cache, CacheContext context) { @@ -362,6 +374,7 @@ public void getAll_function_nullValue(Cache cache, CacheContext contex } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAll_immutable_keys(Cache cache, CacheContext context) { cache.getAll(context.absentKeys(), keys -> { @@ -387,6 +400,7 @@ public void getAll_nullLookup(Cache cache, CacheContext context) { } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getAll_absent_throwsException(Cache cache, CacheContext context) { try { @@ -398,6 +412,7 @@ public void getAll_absent_throwsException(Cache cache, CacheContext co } @CacheSpec + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) public void getAll_function_throwsError(Cache cache, CacheContext context) { try { @@ -906,6 +921,7 @@ private ImmutableSetMultimap, Method> getPublicMethods() { @CacheSpec @CheckNoStats @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") public void stats(Cache cache, CacheContext context) { var stats = cache.stats() .plus(CacheStats.of(1, 2, 3, 4, 5, 6, 7) @@ -917,6 +933,7 @@ public void stats(Cache cache, CacheContext context) { /* --------------- Policy: getIfPresentQuietly --------------- */ @CheckNoStats + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getIfPresentQuietly_nullKey(Cache cache, CacheContext context) { @@ -943,6 +960,7 @@ public void getIfPresentQuietly_present(Cache cache, CacheContext cont /* --------------- Policy: getEntryIfPresentQuietly --------------- */ @CheckNoStats + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getEntryIfPresentQuietly_nullKey(Cache cache, CacheContext context) { @@ -978,6 +996,7 @@ public void refreshes_empty(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void refreshes_unmodifiable(Cache cache, CacheContext context) { cache.policy().refreshes().clear(); @@ -993,6 +1012,7 @@ public void refreshes_nullLookup(Cache cache, CacheContext context) { /* --------------- Policy: CacheEntry --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = UnsupportedOperationException.class) public void cacheEntry_setValue() { SnapshotEntry.forEntry(1, 2).setValue(3); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java index 2e27974ff3..cb3e469266 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java @@ -450,11 +450,13 @@ public void testEqualsAndHashCode() { .testEquals(); } + @SuppressWarnings("CheckReturnValue") public void testMaximumWeight_withWeigher() { Caffeine builder = Caffeine.from(parse("maximumWeight=9000")); builder.weigher((k, v) -> 42).build(k -> null); } + @SuppressWarnings("CheckReturnValue") public void testMaximumWeight_withoutWeigher() { Caffeine builder = Caffeine.from(parse("maximumWeight=9000")); try { @@ -463,11 +465,13 @@ public void testMaximumWeight_withoutWeigher() { } catch (IllegalStateException expected) {} } + @SuppressWarnings("CheckReturnValue") public void testMaximumSize_withWeigher() { Caffeine builder = Caffeine.from(parse("maximumSize=9000")); builder.weigher((k, v) -> 42).build(k -> null); } + @SuppressWarnings("CheckReturnValue") public void testMaximumSize_withoutWeigher() { Caffeine builder = Caffeine.from(parse("maximumSize=9000")); builder.build(k -> null); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java index 7cfef2417d..b331bc0b46 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java @@ -53,16 +53,19 @@ public final class CaffeineSpecTest { static final long UNSET_LONG = UNSET_INT; + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void parseInt_exception() { CaffeineSpec.parseInt("key", "value"); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void parseLong_exception() { CaffeineSpec.parseLong("key", "value"); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void parseTimeUnit_exception() { CaffeineSpec.parseTimeUnit("key", "value"); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java index 8d6870352d..72e929fae2 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java @@ -93,6 +93,7 @@ public void configured() { .isNotEqualTo(Caffeine.newBuilder().maximumWeight(1).toString()); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void fromSpec_null() { Caffeine.from((CaffeineSpec) null); @@ -100,7 +101,8 @@ public void fromSpec_null() { @Test public void fromSpec_lenientParsing() { - Caffeine.from(CaffeineSpec.parse("maximumSize=100")).weigher((k, v) -> 0).build(); + var cache = Caffeine.from(CaffeineSpec.parse("maximumSize=100")).weigher((k, v) -> 0).build(); + assertThat(cache).isNotNull(); } @Test @@ -108,6 +110,7 @@ public void fromSpec() { assertThat(Caffeine.from(CaffeineSpec.parse(""))).isNotNull(); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void fromString_null() { Caffeine.from((String) null); @@ -115,7 +118,8 @@ public void fromString_null() { @Test public void fromString_lenientParsing() { - Caffeine.from("maximumSize=100").weigher((k, v) -> 0).build(); + var cache = Caffeine.from("maximumSize=100").weigher((k, v) -> 0).build(); + assertThat(cache).isNotNull(); } @Test @@ -176,6 +180,7 @@ public void calculateHashMapCapacity() { /* --------------- loading --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void loading_nullLoader() { Caffeine.newBuilder().build(null); @@ -183,16 +188,19 @@ public void loading_nullLoader() { /* --------------- async --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void async_weakValues() { Caffeine.newBuilder().weakValues().buildAsync(loader); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void async_softValues() { Caffeine.newBuilder().softValues().buildAsync(loader); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void async_weakKeys_evictionListener() { RemovalListener evictionListener = (k, v, c) -> {}; @@ -202,6 +210,7 @@ public void async_weakKeys_evictionListener() { /* --------------- async loader --------------- */ @Test + @SuppressWarnings("CheckReturnValue") public void asyncLoader_nullLoader() { try { Caffeine.newBuilder().buildAsync((CacheLoader) null); @@ -217,19 +226,23 @@ public void asyncLoader_nullLoader() { @Test @SuppressWarnings("UnnecessaryMethodReference") public void asyncLoader() { - Caffeine.newBuilder().buildAsync(loader::asyncLoad); + var cache = Caffeine.newBuilder().buildAsync(loader::asyncLoad); + assertThat(cache).isNotNull(); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void asyncLoader_weakValues() { Caffeine.newBuilder().weakValues().buildAsync(loader); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void asyncLoader_softValues() { Caffeine.newBuilder().softValues().buildAsync(loader); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void async_asyncLoader_weakKeys_evictionListener() { RemovalListener evictionListener = (k, v, c) -> {}; @@ -253,7 +266,7 @@ public void initialCapacity_small() { // can't check, so just assert that it builds var builder = Caffeine.newBuilder().initialCapacity(0); assertThat(builder.initialCapacity).isEqualTo(0); - builder.build(); + assertThat(builder.build()).isNotNull(); } @Test @@ -313,6 +326,7 @@ public void maximumWeight_twice() { Caffeine.newBuilder().maximumWeight(1).maximumWeight(1); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void maximumWeight_noWeigher() { Caffeine.newBuilder().maximumWeight(1).build(); @@ -363,6 +377,7 @@ public void weigher_maximumSize() { Caffeine.newBuilder().maximumSize(1).weigher(Weigher.singletonWeigher()); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void weigher_noMaximumWeight() { Caffeine.newBuilder().weigher(Weigher.singletonWeigher()).build(); @@ -373,7 +388,7 @@ public void weigher() { Weigher weigher = (k, v) -> 0; var builder = Caffeine.newBuilder().maximumWeight(0).weigher(weigher); assertThat(builder.weigher).isSameInstanceAs(weigher); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- expireAfterAccess --------------- */ @@ -555,7 +570,7 @@ public void expireAfter_write() { public void expireAfter() { var builder = Caffeine.newBuilder().expireAfter(expiry); assertThat(builder.expiry).isSameInstanceAs(expiry); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- refreshAfterWrite --------------- */ @@ -571,6 +586,7 @@ public void refreshAfterWrite_twice() { .refreshAfterWrite(1, TimeUnit.MILLISECONDS); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void refreshAfterWrite_noCacheLoader() { Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MILLISECONDS).build(); @@ -586,7 +602,7 @@ public void refreshAfterWrite() { var builder = Caffeine.newBuilder() .refreshAfterWrite(1, TimeUnit.MILLISECONDS); assertThat(builder.getRefreshAfterWriteNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(1)); - builder.build(k -> k); + assertThat(builder.build(k -> k)).isNotNull(); } /* --------------- refreshAfterWrite: java.time --------------- */ @@ -602,6 +618,7 @@ public void refreshAfterWrite_duration_twice() { .refreshAfterWrite(Duration.ofMillis(1)); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void refreshAfterWrite_duration_noCacheLoader() { Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(1)).build(); @@ -616,14 +633,14 @@ public void refreshAfterWrite_duration_zero() { public void refreshAfterWrite_duration() { var builder = Caffeine.newBuilder().refreshAfterWrite(Duration.ofMinutes(1)); assertThat(builder.getRefreshAfterWriteNanos()).isEqualTo(Duration.ofMinutes(1).toNanos()); - builder.build(k -> k); + assertThat(builder.build(k -> k)).isNotNull(); } @Test public void refreshAfterWrite_excessive() { var builder = Caffeine.newBuilder().refreshAfterWrite(ChronoUnit.FOREVER.getDuration()); assertThat(builder.getRefreshAfterWriteNanos()).isEqualTo(Long.MAX_VALUE); - builder.build(k -> k); + assertThat(builder.build(k -> k)).isNotNull(); } /* --------------- weakKeys --------------- */ @@ -635,7 +652,8 @@ public void weakKeys_twice() { @Test public void weakKeys() { - Caffeine.newBuilder().weakKeys().build(); + var cache = Caffeine.newBuilder().weakKeys().build(); + assertThat(cache).isNotNull(); } /* --------------- weakValues --------------- */ @@ -647,7 +665,8 @@ public void weakValues_twice() { @Test public void weakValues() { - Caffeine.newBuilder().weakValues().build(); + var cache = Caffeine.newBuilder().weakValues().build(); + assertThat(cache).isNotNull(); } /* --------------- softValues --------------- */ @@ -659,7 +678,8 @@ public void softValues_twice() { @Test public void softValues() { - Caffeine.newBuilder().softValues().build(); + var cache = Caffeine.newBuilder().softValues().build(); + assertThat(cache).isNotNull(); } /* --------------- scheduler --------------- */ @@ -679,7 +699,7 @@ public void scheduler_twice() { public void scheduler_system() { var builder = Caffeine.newBuilder().scheduler(Scheduler.systemScheduler()); assertThat(builder.getScheduler()).isSameInstanceAs(Scheduler.systemScheduler()); - builder.build(); + assertThat(builder.build()).isNotNull(); } @Test @@ -687,7 +707,7 @@ public void scheduler_custom() { Scheduler scheduler = (executor, task, delay, unit) -> DisabledFuture.INSTANCE; var builder = Caffeine.newBuilder().scheduler(scheduler); assertThat(((GuardedScheduler) builder.getScheduler()).delegate).isSameInstanceAs(scheduler); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- executor --------------- */ @@ -707,7 +727,7 @@ public void executor_twice() { public void executor() { var builder = Caffeine.newBuilder().executor(directExecutor()); assertThat(builder.getExecutor()).isSameInstanceAs(directExecutor()); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- ticker --------------- */ @@ -727,7 +747,7 @@ public void ticker() { Ticker ticker = new FakeTicker()::read; var builder = Caffeine.newBuilder().ticker(ticker); assertThat(builder.ticker).isSameInstanceAs(ticker); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- stats --------------- */ @@ -758,7 +778,7 @@ public void recordStats_twice() { public void recordStats() { var builder = Caffeine.newBuilder().recordStats(); assertThat(builder.statsCounterSupplier).isEqualTo(Caffeine.ENABLED_STATS_COUNTER_SUPPLIER); - builder.build(); + assertThat(builder.build()).isNotNull(); } @Test @@ -767,7 +787,7 @@ public void recordStats_custom() { var builder = Caffeine.newBuilder().recordStats(supplier); builder.statsCounterSupplier.get().recordEviction(1, RemovalCause.SIZE); verify(statsCounter).recordEviction(1, RemovalCause.SIZE); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- removalListener --------------- */ @@ -787,7 +807,7 @@ public void removalListener() { RemovalListener removalListener = (k, v, c) -> {}; var builder = Caffeine.newBuilder().removalListener(removalListener); assertThat(builder.getRemovalListener(false)).isSameInstanceAs(removalListener); - builder.build(); + assertThat(builder.build()).isNotNull(); } /* --------------- removalListener --------------- */ @@ -807,6 +827,6 @@ public void evictionListener() { RemovalListener removalListener = (k, v, c) -> {}; var builder = Caffeine.newBuilder().evictionListener(removalListener); assertThat(builder.evictionListener).isSameInstanceAs(removalListener); - builder.build(); + assertThat(builder.build()).isNotNull(); } } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java index f1d57a4aa3..c93bd33f88 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java @@ -859,6 +859,7 @@ public void coldest_unmodifiable(CacheContext context, Eviction evicti eviction.coldest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(maximumSize = Maximum.FULL) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void coldest_negative(CacheContext context, Eviction eviction) { @@ -902,6 +903,7 @@ public void coldest_snapshot(Cache cache, assertThat(coldest).containsExactlyEntriesIn(context.original()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_null(CacheContext context, Eviction eviction) { @@ -916,6 +918,7 @@ public void coldestFunc_nullResult(CacheContext context, Eviction evic } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_throwsException(CacheContext context, Eviction eviction) { var expected = new IllegalStateException(); @@ -927,6 +930,7 @@ public void coldestFunc_throwsException(CacheContext context, Eviction } } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_concurrentModification(Cache cache, @@ -995,6 +999,7 @@ public void coldestWeight_unmodifiable(CacheContext context, Eviction eviction.coldestWeighted(Long.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(maximumSize = Maximum.FULL) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void coldestWeighted_negative(CacheContext context, Eviction eviction) { @@ -1062,6 +1067,7 @@ public void hottest_unmodifiable(CacheContext context, Eviction evicti eviction.hottest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(maximumSize = Maximum.FULL) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void hottest_negative(CacheContext context, Eviction eviction) { @@ -1105,6 +1111,7 @@ public void hottest_snapshot(Cache cache, assertThat(hottest).containsExactlyEntriesIn(context.original()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_null(CacheContext context, Eviction eviction) { @@ -1119,6 +1126,7 @@ public void hottestFunc_nullResult(CacheContext context, Eviction evic } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_throwsException(CacheContext context, Eviction eviction) { var expected = new IllegalStateException(); @@ -1130,6 +1138,7 @@ public void hottestFunc_throwsException(CacheContext context, Eviction } } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_concurrentModification(Cache cache, @@ -1207,6 +1216,7 @@ public void hottestWeighted_unmodifiable(CacheContext context, Eviction eviction) { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java index cb295b0dec..72035a2e75 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java @@ -218,15 +218,13 @@ public void schedule_delay(Cache cache, CacheContext context) { expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE}) public void get_writeTime(Cache cache, CacheContext context) { - Int key = context.absentKey(); - Int value = context.absentValue(); - - cache.get(key, k -> { + var value = cache.get(context.absentKey(), k -> { context.ticker().advance(5, TimeUnit.MINUTES); - return value; + return context.absentValue(); }); assertThat(cache).hasSize(1); - assertThat(cache).containsEntry(key, value); + assertThat(value).isEqualTo(context.absentValue()); + assertThat(cache).containsEntry(context.absentKey(), context.absentValue()); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java index a17a5cd97a..4c3b7fd2a9 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java @@ -78,7 +78,9 @@ public final class ExpireAfterAccessTest { expireAfterAccess = Expire.ONE_MINUTE, population = { Population.PARTIAL, Population.FULL }) public void getIfPresent(Cache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.getIfPresent(context.firstKey()); + var value = cache.getIfPresent(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.getIfPresent(context.firstKey())).isEqualTo(context.firstKey().negate()); assertThat(cache.getIfPresent(context.lastKey())).isNull(); @@ -99,10 +101,15 @@ public void getIfPresent(Cache cache, CacheContext context) { public void get(Cache cache, CacheContext context) { Function mappingFunction = context.original()::get; context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey(), mappingFunction); + var value1 = cache.get(context.firstKey(), mappingFunction); + assertThat(value1).isEqualTo(context.original().get(context.firstKey())); + context.ticker().advance(45, TimeUnit.SECONDS); - cache.get(context.firstKey(), mappingFunction); - cache.get(context.lastKey(), mappingFunction); // recreated + var value2 = cache.get(context.firstKey(), mappingFunction); + assertThat(value2).isEqualTo(context.original().get(context.firstKey())); + + var value3 = cache.get(context.lastKey(), mappingFunction); // recreated + assertThat(value3).isEqualTo(context.original().get(context.lastKey())); cache.cleanUp(); assertThat(cache).hasSize(2); @@ -119,7 +126,9 @@ public void get(Cache cache, CacheContext context) { expireAfterAccess = Expire.ONE_MINUTE, population = { Population.PARTIAL, Population.FULL }) public void getAllPresent(Cache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.getAllPresent(context.firstMiddleLastKeys()); + var results = cache.getAllPresent(context.firstMiddleLastKeys()); + assertThat(results).hasSize(3); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.getAllPresent(context.firstMiddleLastKeys())).hasSize(3); @@ -172,7 +181,9 @@ public void getAll(Cache cache, CacheContext context) { loader = Loader.IDENTITY, population = { Population.PARTIAL, Population.FULL }) public void get_loading(LoadingCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.get(context.lastKey())).isEqualTo(context.lastKey()); cache.cleanUp(); @@ -268,7 +279,9 @@ public void getIfPresentQuietly(Cache cache, CacheContext context, var original = expireAfterAccess.ageOf(context.firstKey()).orElseThrow(); var advancement = Duration.ofSeconds(30); context.ticker().advance(advancement); - cache.policy().getIfPresentQuietly(context.firstKey()); + var value = cache.policy().getIfPresentQuietly(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + var current = cache.policy().expireAfterAccess() .flatMap(policy -> policy.ageOf(context.firstKey())).orElseThrow(); assertThat(current.minus(advancement)).isEqualTo(original); @@ -371,6 +384,7 @@ public void ageOf_expired(Cache cache, CacheContext context, /* --------------- Policy: oldest --------------- */ + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void oldest_unmodifiable(CacheContext context, @@ -378,6 +392,7 @@ public void oldest_unmodifiable(CacheContext context, expireAfterAccess.oldest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void oldest_negative(CacheContext context, @@ -419,6 +434,7 @@ public void oldest_snapshot(Cache cache, CacheContext context, assertThat(oldest).containsExactlyEntriesIn(context.original()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void oldestFunc_null(CacheContext context, @@ -435,6 +451,7 @@ public void oldestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void oldestFunc_throwsException(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { @@ -447,8 +464,9 @@ public void oldestFunc_throwsException(CacheContext context, } } - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void oldestFunc_concurrentModification(Cache cache, CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { expireAfterAccess.oldest(stream -> { @@ -518,6 +536,7 @@ public void oldestFunc_metadata_expiresInTraversal(CacheContext context, /* --------------- Policy: youngest --------------- */ + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void youngest_unmodifiable(CacheContext context, @@ -525,6 +544,7 @@ public void youngest_unmodifiable(CacheContext context, expireAfterAccess.youngest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void youngest_negative(CacheContext context, @@ -567,6 +587,7 @@ public void youngest_snapshot(Cache cache, CacheContext context, assertThat(youngest).containsExactlyEntriesIn(context.original()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void youngestFunc_null(CacheContext context, @@ -583,6 +604,7 @@ public void youngestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void youngestFunc_throwsException(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { @@ -595,8 +617,9 @@ public void youngestFunc_throwsException(CacheContext context, } } - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void youngestFunc_concurrentModification(Cache cache, CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { expireAfterAccess.youngest(stream -> { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java index 51192cb73e..88fd3cbc78 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java @@ -101,7 +101,8 @@ public void expiry_bounds(Cache cache, CacheContext context) { ConcurrentTestHarness.execute(() -> { while (!done.get()) { context.ticker().advance(1, TimeUnit.MINUTES); - cache.get(key, Int::new); + var value = cache.get(key, Int::new); + assertThat(value).isSameInstanceAs(key); running.set(true); } }); @@ -119,7 +120,8 @@ public void expiry_bounds(Cache cache, CacheContext context) { @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) public void getIfPresent(Cache cache, CacheContext context) { - cache.getIfPresent(context.firstKey()); + var value = cache.getIfPresent(context.firstKey()); + assertThat(value).isNotNull(); verify(context.expiry()).expireAfterRead(any(), any(), anyLong(), anyLong()); verifyNoMoreInteractions(context.expiry()); @@ -128,7 +130,8 @@ public void getIfPresent(Cache cache, CacheContext context) { @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) public void get(LoadingCache cache, CacheContext context) { - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); verify(context.expiry()).expireAfterRead(any(), any(), anyLong(), anyLong()); verifyNoMoreInteractions(context.expiry()); @@ -137,7 +140,8 @@ public void get(LoadingCache cache, CacheContext context) { @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) public void getAll_present(LoadingCache cache, CacheContext context) { - cache.getAll(context.firstMiddleLastKeys()); + var results = cache.getAll(context.firstMiddleLastKeys()); + assertThat(results).isNotEmpty(); verify(context.expiry(), times(3)).expireAfterRead(any(), any(), anyLong(), anyLong()); verifyNoMoreInteractions(context.expiry()); @@ -147,7 +151,8 @@ public void getAll_present(LoadingCache cache, CacheContext context) { @CacheSpec(population = Population.EMPTY, expiry = CacheExpiry.MOCKITO, loader = {Loader.IDENTITY, Loader.BULK_IDENTITY}) public void getAll_absent(LoadingCache cache, CacheContext context) { - cache.getAll(context.absentKeys()); + var results = cache.getAll(context.absentKeys()); + assertThat(results).isNotEmpty(); verify(context.expiry(), times(context.absent().size())) .expireAfterCreate(any(), any(), anyLong()); @@ -310,6 +315,7 @@ public void replaceConditionally_expiryFails(Map map, CacheContext con /* --------------- Exceptional --------------- */ + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void getIfPresent_expiryFails(Cache cache, CacheContext context) { @@ -324,6 +330,7 @@ public void getIfPresent_expiryFails(Cache cache, CacheContext context } } + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_create(Cache cache, CacheContext context) { @@ -338,6 +345,7 @@ public void get_expiryFails_create(Cache cache, CacheContext context) } } + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_read(Cache cache, CacheContext context) { @@ -352,6 +360,7 @@ public void get_expiryFails_read(Cache cache, CacheContext context) { } } + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void getAllPresent_expiryFails(Cache cache, CacheContext context) { @@ -596,7 +605,8 @@ public void getIfPresentQuietly(Cache cache, CacheContext context) { .getExpiresAfter(context.firstKey()).orElseThrow(); var advancement = Duration.ofSeconds(30); context.ticker().advance(advancement); - cache.policy().getIfPresentQuietly(context.firstKey()); + var value = cache.policy().getIfPresentQuietly(context.firstKey()); + assertThat(value).isNotNull(); var current = cache.policy().expireVariably().orElseThrow() .getExpiresAfter(context.firstKey()).orElseThrow(); assertThat(current.plus(advancement)).isEqualTo(original); @@ -736,45 +746,50 @@ public void setExpiresAfter_expired(Cache cache, /* --------------- Policy: putIfAbsent --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullKey(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.putIfAbsent(null, Int.valueOf(2), 3, TimeUnit.SECONDS); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullValue(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.putIfAbsent(Int.valueOf(1), null, 3, TimeUnit.SECONDS); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullTimeUnit(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), 3, null); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void putIfAbsent_negativeDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), -10, TimeUnit.SECONDS); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), null); @@ -786,8 +801,9 @@ public void putIfAbsent_nullDuration(Cache cache, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void putIfAbsent_excessiveDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.putIfAbsent(context.absentKey(), + var oldValue = expireAfterVar.putIfAbsent(context.absentKey(), context.absentValue(), ChronoUnit.FOREVER.getDuration()); + assertThat(oldValue).isNull(); assertThat(expireAfterVar.getExpiresAfter(context.absentKey(), TimeUnit.NANOSECONDS)) .hasValue(MAXIMUM_EXPIRY); } @@ -831,36 +847,40 @@ public void putIfAbsent_present(Cache cache, /* --------------- Policy: put --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullKey(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.put(null, Int.valueOf(2), 3, TimeUnit.SECONDS); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullValue(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.put(Int.valueOf(1), null, 3, TimeUnit.SECONDS); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullTimeUnit(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), 3, null); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void put_negativeDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), -10, TimeUnit.SECONDS); @@ -872,16 +892,18 @@ public void put_negativeDuration(Cache cache, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void put_excessiveDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.put(context.absentKey(), + var oldValue = expireAfterVar.put(context.absentKey(), context.absentValue(), ChronoUnit.FOREVER.getDuration()); + assertThat(oldValue).isNull(); assertThat(expireAfterVar.getExpiresAfter(context.absentKey(), TimeUnit.NANOSECONDS)) .hasValue(MAXIMUM_EXPIRY); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), null); @@ -925,13 +947,15 @@ public void put_replace(Cache cache, /* --------------- Policy: compute --------------- */ - @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) public void compute_nullKey(CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.compute(null, (key, value) -> key.negate(), Duration.ZERO); } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) public void compute_nullMappingFunction(CacheContext context, @@ -940,6 +964,7 @@ public void compute_nullMappingFunction(CacheContext context, } @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) public void compute_negativeDuration( @@ -952,8 +977,9 @@ public void compute_negativeDuration( expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void compute_excessiveDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.absentKey(), + var value = expireAfterVar.compute(context.absentKey(), (k, v) -> context.absentValue(), ChronoUnit.FOREVER.getDuration()); + assertThat(value).isNotNull(); assertThat(expireAfterVar.getExpiresAfter(context.absentKey(), TimeUnit.NANOSECONDS)) .hasValue(MAXIMUM_EXPIRY); } @@ -982,6 +1008,7 @@ public void compute_remove(Cache cache, } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) public void compute_recursive(CacheContext context, VarExpiration expireAfterVar) { var mappingFunction = new BiFunction() { @@ -996,6 +1023,7 @@ public void compute_recursive(CacheContext context, VarExpiration expi } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS, population = Population.EMPTY) public void compute_pingpong(CacheContext context, VarExpiration expireAfterVar) { var key1 = Int.valueOf(1); @@ -1012,6 +1040,7 @@ public void compute_pingpong(CacheContext context, VarExpiration expir } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.MOCKITO) public void compute_error(Cache cache, CacheContext context, VarExpiration expireAfterVar) { @@ -1067,8 +1096,9 @@ public void compute_absent(Cache cache, @CacheSpec(expiry = CacheExpiry.MOCKITO) public void compute_absent_expires(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.absentKey(), + var value = expireAfterVar.compute(context.absentKey(), (k, v) -> context.absentValue(), Duration.ofMinutes(1)); + assertThat(value).isNotNull(); context.ticker().advance(Duration.ofMinutes(5)); context.cleanUp(); @@ -1083,7 +1113,9 @@ public void compute_absent_expires(Cache cache, @CacheSpec(expiry = CacheExpiry.MOCKITO) public void compute_absent_expiresImmediately(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.absentKey(), (k, v) -> context.absentValue(), Duration.ZERO); + var value = expireAfterVar.compute(context.absentKey(), + (k, v) -> context.absentValue(), Duration.ZERO); + assertThat(value).isNotNull(); assertThat(cache).doesNotContainKey(context.absentKey()); context.ticker().advance(Duration.ofMinutes(1)); context.cleanUp(); @@ -1098,8 +1130,9 @@ public void compute_absent_expiresImmediately(Cache cache, @CacheSpec(expiry = CacheExpiry.MOCKITO, expiryTime = Expire.ONE_MINUTE) public void compute_absent_expiresLater(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.absentKey(), + var value = expireAfterVar.compute(context.absentKey(), (k, v) -> context.absentValue(), Duration.ofMinutes(5)); + assertThat(value).isNotNull(); context.ticker().advance(Duration.ofMinutes(3)); context.cleanUp(); @@ -1195,10 +1228,11 @@ public void compute_differentValue(Cache cache, population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void compute_present_expires(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.firstKey(), (k, v) -> { + var value = expireAfterVar.compute(context.firstKey(), (k, v) -> { assertThat(v).isNotNull(); return context.absentValue(); }, Duration.ofMinutes(1)); + assertThat(value).isNotNull(); context.ticker().advance(Duration.ofMinutes(5)); context.cleanUp(); @@ -1219,10 +1253,11 @@ public void compute_present_expires(Cache cache, population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void compute_present_expiresImmediately(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.firstKey(), (k, v) -> { + var value = expireAfterVar.compute(context.firstKey(), (k, v) -> { assertThat(v).isNotNull(); return context.absentValue(); }, Duration.ZERO); + assertThat(value).isNotNull(); assertThat(cache).doesNotContainKey(context.firstKey()); context.ticker().advance(Duration.ofMinutes(1)); context.cleanUp(); @@ -1243,10 +1278,11 @@ public void compute_present_expiresImmediately(Cache cache, population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void compute_present_expiresLater(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(context.firstKey(), (k, v) -> { + var value = expireAfterVar.compute(context.firstKey(), (k, v) -> { assertThat(v).isNotNull(); return context.absentValue(); }, Duration.ofMinutes(5)); + assertThat(value).isNotNull(); context.ticker().advance(Duration.ofMinutes(3)); context.cleanUp(); @@ -1298,16 +1334,19 @@ public void compute_writeTime(Cache cache, Int value = context.absentValue(); var duration = Duration.ofNanos(context.expiryTime().timeNanos()); - expireAfterVar.compute(key, (k, v) -> { + var computed = expireAfterVar.compute(key, (k, v) -> { context.ticker().advance(5, TimeUnit.MINUTES); return value; }, duration); + assertThat(computed).isNotNull(); + context.cleanUp(); assertThat(cache).hasSize(1); assertThat(cache).containsKey(key); } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void compute_absent_error(CacheContext context, VarExpiration expireAfterVar) { @@ -1322,6 +1361,7 @@ public void compute_absent_error(CacheContext context, VarExpiration e } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, compute = Compute.SYNC, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void compute_present_error(CacheContext context, VarExpiration expireAfterVar) { @@ -1368,6 +1408,7 @@ public void oldest_unmodifiable(CacheContext context, VarExpiration ex expireAfterVar.oldest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void oldest_negative(CacheContext context, VarExpiration expireAfterVar) { @@ -1404,8 +1445,9 @@ public void oldest_snapshot(Cache cache, assertThat(oldest).containsExactlyEntriesIn(context.original()); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void oldestFunc_null(CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.oldest(null); } @@ -1418,6 +1460,7 @@ public void oldestFunc_nullResult(CacheContext context, VarExpiration } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) public void oldestFunc_throwsException(CacheContext context, VarExpiration expireAfterVar) { @@ -1430,8 +1473,9 @@ public void oldestFunc_throwsException(CacheContext context, } } - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) + @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void oldestFunc_concurrentModification(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.oldest(stream -> { @@ -1506,6 +1550,7 @@ public void youngest_unmodifiable(CacheContext context, VarExpiration expireAfterVar.youngest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void youngest_negative(CacheContext context, VarExpiration expireAfterVar) { @@ -1543,8 +1588,9 @@ public void youngest_snapshot(Cache cache, assertThat(youngest).containsExactlyEntriesIn(context.original()); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) + @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void youngestFunc_null(CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.youngest(null); } @@ -1558,6 +1604,7 @@ public void youngestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) public void youngestFunc_throwsException(CacheContext context, VarExpiration expireAfterVar) { @@ -1570,8 +1617,9 @@ public void youngestFunc_throwsException(CacheContext context, } } - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) + @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void youngestFunc_concurrentModification(Cache cache, CacheContext context, VarExpiration expireAfterVar) { expireAfterVar.youngest(stream -> { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java index e9737becac..99431a3e0d 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java @@ -72,6 +72,7 @@ public final class ExpireAfterWriteTest { /* --------------- Cache --------------- */ @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = { Expire.DISABLED, Expire.ONE_MINUTE }, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE, @@ -89,6 +90,7 @@ public void getIfPresent(Cache cache, CacheContext context) { } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) @@ -106,6 +108,7 @@ public void get(Cache cache, CacheContext context) { } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) @@ -147,6 +150,7 @@ public void getAll(Cache cache, CacheContext context) { /* --------------- LoadingCache --------------- */ @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) @@ -226,6 +230,7 @@ public void putIfAbsent(Map map, CacheContext context) { @CheckNoStats @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expireAfterWrite = Expire.ONE_MINUTE) public void getIfPresentQuietly(Cache cache, CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { @@ -342,6 +347,7 @@ public void oldest_unmodifiable(CacheContext context, expireAfterWrite.oldest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void oldest_negative(CacheContext context, @@ -383,6 +389,7 @@ public void oldest_snapshot(Cache cache, CacheContext context, assertThat(oldest).containsExactlyEntriesIn(context.original()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_null(CacheContext context, @@ -399,6 +406,7 @@ public void oldestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_throwsException(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { @@ -411,6 +419,7 @@ public void oldestFunc_throwsException(CacheContext context, } } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_concurrentModification(Cache cache, @@ -489,6 +498,7 @@ public void youngest_unmodifiable(CacheContext context, expireAfterWrite.youngest(Integer.MAX_VALUE).clear(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void youngest_negative(CacheContext context, @@ -531,6 +541,7 @@ public void youngest_snapshot(Cache cache, CacheContext context, assertThat(youngest).containsExactlyEntriesIn(context.original()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_null(CacheContext context, @@ -547,6 +558,7 @@ public void youngestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_throwsException(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { @@ -559,6 +571,7 @@ public void youngestFunc_throwsException(CacheContext context, } } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_concurrentModification(Cache cache, diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java index cb88d6ed40..b77602ff06 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java @@ -63,6 +63,7 @@ public static TestSuite suite() { .createTestSuite(); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "interners", expectedExceptions = NullPointerException.class) public void intern_null(Interner interner) { interner.intern(null); @@ -123,11 +124,13 @@ public void intern_weak_cleanup() { interner.cache.drainStatus = BoundedLocalCache.REQUIRED; var canonical = new Int(1); - interner.intern(canonical); + var interned1 = interner.intern(canonical); + assertThat(interned1).isSameInstanceAs(canonical); assertThat(interner.cache.drainStatus).isEqualTo(BoundedLocalCache.IDLE); interner.cache.drainStatus = BoundedLocalCache.REQUIRED; - interner.intern(canonical); + var interned2 = interner.intern(canonical); + assertThat(interned2).isSameInstanceAs(canonical); assertThat(interner.cache.drainStatus).isEqualTo(BoundedLocalCache.IDLE); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java index a4b2723412..7c29a86699 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java @@ -93,6 +93,7 @@ public final class LoadingCacheTest { @CacheSpec @CheckNoEvictions @CheckNoStats + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_null(LoadingCache cache, CacheContext context) { cache.get(null); @@ -107,6 +108,7 @@ public void get_absent_null(LoadingCache cache, CacheContext context) } @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = Loader.EXCEPTIONAL) @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void get_absent_throwsException(LoadingCache cache, CacheContext context) { @@ -119,6 +121,7 @@ public void get_absent_throwsException(LoadingCache cache, CacheContex @CheckNoEvictions @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = Loader.CHECKED_EXCEPTIONAL) public void get_absent_throwsCheckedException( LoadingCache cache, CacheContext context) { @@ -133,6 +136,7 @@ public void get_absent_throwsCheckedException( @CheckNoEvictions @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(compute = Compute.SYNC, loader = Loader.INTERRUPTED) public void get_absent_interrupted(LoadingCache cache, CacheContext context) { try { @@ -167,6 +171,7 @@ public void get_present(LoadingCache cache, CacheContext context) { /* --------------- getAll --------------- */ @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_null(LoadingCache cache, CacheContext context) { @@ -174,6 +179,7 @@ public void getAll_iterable_null(LoadingCache cache, CacheContext cont } @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.NEGATIVE, Loader.BULK_NEGATIVE }, removalListener = { Listener.DISABLED, Listener.REJECTING }) @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) @@ -191,6 +197,7 @@ public void getAll_iterable_empty(LoadingCache cache, CacheContext con } @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = Loader.BULK_MODIFY_KEYS) @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAll_immutable_keys(LoadingCache cache, CacheContext context) { @@ -199,6 +206,7 @@ public void getAll_immutable_keys(LoadingCache cache, CacheContext con @CacheSpec @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAll_immutable_result(LoadingCache cache, CacheContext context) { cache.getAll(context.firstMiddleLastKeys()).clear(); @@ -221,6 +229,7 @@ public void getAll_absent_null(LoadingCache cache, CacheContext contex } @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = Loader.BULK_NULL) @Test(dataProvider = "caches", expectedExceptions = Exception.class) public void getAll_absent_bulkNull(LoadingCache cache, CacheContext context) { @@ -228,6 +237,7 @@ public void getAll_absent_bulkNull(LoadingCache cache, CacheContext co } @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.EXCEPTIONAL, Loader.BULK_EXCEPTIONAL }) @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getAll_absent_throwsExecption(LoadingCache cache, CacheContext context) { @@ -242,6 +252,7 @@ public void getAll_absent_throwsExecption(LoadingCache cache, CacheCon @CheckNoEvictions @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.CHECKED_EXCEPTIONAL, Loader.BULK_CHECKED_EXCEPTIONAL }) public void getAll_absent_throwsCheckedExecption( LoadingCache cache, CacheContext context) { @@ -258,6 +269,7 @@ public void getAll_absent_throwsCheckedExecption( } @CheckNoEvictions + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.EXCEPTIONAL, Loader.BULK_EXCEPTIONAL }) @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getAll_absent_throwsExecption_iterable( @@ -273,6 +285,7 @@ public void getAll_absent_throwsExecption_iterable( @CheckNoEvictions @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.INTERRUPTED, Loader.BULK_INTERRUPTED }) public void getAll_absent_interrupted(LoadingCache cache, CacheContext context) { try { @@ -1115,6 +1128,7 @@ public void refreshAll_nullFuture_reload(CacheContext context) { /* --------------- CacheLoader --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = UnsupportedOperationException.class) public void loadAll() throws Exception { CacheLoader loader = key -> key; @@ -1180,6 +1194,7 @@ public void asyncReload() throws Exception { assertThat(future).succeedsWith(-1); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void bulk_null() { CacheLoader.bulk(null); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java index 820310f4d4..658f773e04 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java @@ -41,6 +41,7 @@ import com.google.common.collect.Sets; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * Propositions for {@link LocalCache}-based subjects. @@ -313,6 +314,7 @@ private boolean doLinksMatch(BoundedLocalCache bounded, } } + @CanIgnoreReturnValue private long scanLinks(BoundedLocalCache bounded, LinkedDeque> deque, Set> seen) { long weightedSize = 0; diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java index 4a4b9a3ec9..9bf0861435 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java @@ -38,16 +38,19 @@ public final class MpscGrowableArrayQueueTest { /* --------------- Constructor --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void constructor_initialCapacity_tooSmall() { new MpscGrowableArrayQueue(/* initialCapacity */ 1, /* maxCapacity */ 4); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void constructor_maxCapacity_tooSmall() { new MpscGrowableArrayQueue(/* initialCapacity */ 4, /* maxCapacity */ 1); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void constructor_inverted() { new MpscGrowableArrayQueue(/* initialCapacity */ 8, /* maxCapacity */ 4); @@ -162,7 +165,8 @@ public void peek_whenPopulated(MpscGrowableArrayQueue buffer) { public void peek_toEmpty(MpscGrowableArrayQueue buffer) { for (int i = 0; i < FULL_SIZE; i++) { assertThat(buffer.peek()).isNotNull(); - buffer.poll(); + var item = buffer.poll(); + assertThat(item).isNotNull(); } assertThat(buffer.peek()).isNull(); } @@ -182,7 +186,8 @@ public void relaxedPeek_whenPopulated(MpscGrowableArrayQueue buffer) { public void relaxedPeek_toEmpty(MpscGrowableArrayQueue buffer) { for (int i = 0; i < FULL_SIZE; i++) { assertThat(buffer.relaxedPeek()).isNotNull(); - buffer.poll(); + var item = buffer.poll(); + assertThat(item).isNotNull(); } assertThat(buffer.relaxedPeek()).isNull(); } @@ -289,7 +294,7 @@ public Object[][] providesFull() { static MpscGrowableArrayQueue makePopulated(int items) { var buffer = new MpscGrowableArrayQueue(4, FULL_SIZE); for (int i = 0; i < items; i++) { - buffer.offer(i); + buffer.add(i); } return buffer; } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MultiThreadedTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MultiThreadedTest.java index 91888e84b1..0836020460 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MultiThreadedTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MultiThreadedTest.java @@ -159,7 +159,7 @@ public void async_concurrent_bounded( } }); - @SuppressWarnings({"FutureReturnValueIgnored", "MethodReferenceUsage"}) + @SuppressWarnings({"CheckReturnValue", "FutureReturnValueIgnored", "MethodReferenceUsage"}) List, Int>> asyncOperations = List.of( (cache, key) -> { cache.getIfPresent(key); }, (cache, key) -> { cache.get(key, k -> key); }, diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java index c4a5bdcb59..516e9b1f8b 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java @@ -154,6 +154,7 @@ public void get(Cache cache, CacheContext context) { .contains(collected).exclusively(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}) @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) @@ -395,6 +396,7 @@ public void get_loading(LoadingCache cache, CacheContext context) { .contains(collected).exclusively(); } + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}, loader = Loader.IDENTITY) @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java index 031a931732..b8f252545c 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java @@ -85,6 +85,7 @@ public final class RefreshAfterWriteTest { @CheckNoEvictions @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY, refreshAfterWrite = Expire.ONE_MINUTE, executor = CacheExecutor.THREADED) public void refreshIfNeeded_nonblocking(CacheContext context) { @@ -158,7 +159,9 @@ public CompletableFuture asyncReload(Int key, Int oldValue, Executor execut executor = CacheExecutor.DIRECT) public void refreshIfNeeded_interrupted(LoadingCache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + + assertThat(value).isNotNull(); assertThat(Thread.interrupted()).isTrue(); } @@ -168,8 +171,9 @@ public void refreshIfNeeded_interrupted(LoadingCache cache, CacheConte public void refreshIfNeeded_replace(LoadingCache cache, CacheContext context) { cache.put(context.absentKey(), context.absentKey()); context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.absentKey()); + var value = cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); assertThat(cache).containsEntry(context.absentKey(), context.absentValue()); assertThat(context).removalNotifications().withCause(REPLACED) .contains(context.absentKey(), context.absentKey()) @@ -183,8 +187,9 @@ public void refreshIfNeeded_replace(LoadingCache cache, CacheContext c public void refreshIfNeeded_remove(LoadingCache cache, CacheContext context) { cache.put(context.absentKey(), context.absentValue()); context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.absentKey()); + var value = cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); assertThat(cache).doesNotContainKey(context.absentKey()); assertThat(context).removalNotifications().withCause(EXPLICIT) .contains(context.absentKey(), context.absentValue()) @@ -207,8 +212,9 @@ public void refreshIfNeeded_noChange(CacheContext context) { }); cache.put(context.absentKey(), context.absentValue()); context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.absentKey()); + var value = cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); assertThat(context).removalNotifications().isEmpty(); } @@ -219,7 +225,8 @@ public void refreshIfNeeded_noChange(CacheContext context) { loader = Loader.ASYNC_INCOMPLETE) public void refreshIfNeeded_replaced(LoadingCache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); assertThat(cache.policy().refreshes()).isNotEmpty(); var future = cache.policy().refreshes().get(context.firstKey()); @@ -244,7 +251,8 @@ public void refreshIfNeeded_replaced(LoadingCache cache, CacheContext expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE}) public void refreshIfNeeded_expired(LoadingCache cache, CacheContext context) { context.ticker().advance(10, TimeUnit.SECONDS); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); assertThat(cache.policy().refreshes()).isNotEmpty(); var future = cache.policy().refreshes().get(context.firstKey()); @@ -267,7 +275,8 @@ public void refreshIfNeeded_expired(LoadingCache cache, CacheContext c loader = Loader.ASYNC_INCOMPLETE) public void refreshIfNeeded_absent_newValue(LoadingCache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); assertThat(cache.policy().refreshes()).isNotEmpty(); var future = cache.policy().refreshes().get(context.firstKey()); @@ -292,7 +301,8 @@ public void refreshIfNeeded_absent_newValue(LoadingCache cache, CacheC loader = Loader.ASYNC_INCOMPLETE, executor = CacheExecutor.THREADED) public void refreshIfNeeded_absent_nullValue(LoadingCache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); assertThat(cache.policy().refreshes()).isNotEmpty(); var future = cache.policy().refreshes().get(context.firstKey()); @@ -327,8 +337,9 @@ public void refreshIfNeeded_cancel_noLog(CacheContext context) { : context.build(cacheLoader); cache.put(context.absentKey(), context.absentValue()); context.ticker().advance(2, TimeUnit.MINUTES); + var value = cache.get(context.absentKey()); - cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); assertThat(TestLoggerFactory.getLoggingEvents()).isEmpty(); } @@ -354,8 +365,9 @@ public void refreshIfNeeded_timeout_noLog(CacheContext context) { : context.build(cacheLoader); cache.put(context.absentKey(), context.absentValue()); context.ticker().advance(2, TimeUnit.MINUTES); + var value = cache.get(context.absentKey()); - cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); assertThat(TestLoggerFactory.getLoggingEvents()).isEmpty(); } @@ -371,8 +383,9 @@ public void refreshIfNeeded_error_log(CacheContext context) { : context.build(cacheLoader); cache.put(context.absentKey(), context.absentValue()); context.ticker().advance(2, TimeUnit.MINUTES); + var value = cache.get(context.absentKey()); - cache.get(context.absentKey()); + assertThat(value).isEqualTo(context.absentValue()); var event = Iterables.getOnlyElement(TestLoggerFactory.getLoggingEvents()); assertThat(event.getThrowable().orElseThrow()).hasCauseThat().isSameInstanceAs(expected); assertThat(event.getLevel()).isEqualTo(WARN); @@ -399,8 +412,9 @@ public void refreshIfNeeded_nullFuture(CacheContext context) { : context.build(loader); cache.put(context.absentKey(), context.absentValue()); context.ticker().advance(2, TimeUnit.MINUTES); - cache.get(context.absentKey()); + var value = cache.get(context.absentKey()); + assertThat(value).isNotNull(); var event = Iterables.getOnlyElement(TestLoggerFactory.getLoggingEvents()); assertThat(event.getThrowable().orElseThrow()).isInstanceOf(NullPointerException.class); assertThat(event.getLevel()).isEqualTo(WARN); @@ -473,7 +487,9 @@ public void getIfPresent_async(AsyncLoadingCache cache, CacheContext c population = { Population.PARTIAL, Population.FULL }) public void getAllPresent_immediate(LoadingCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.getAllPresent(context.firstMiddleLastKeys()); + var results = cache.getAllPresent(context.firstMiddleLastKeys()); + + assertThat(results).isNotEmpty(); context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.getAllPresent(context.firstMiddleLastKeys())) .containsExactlyEntriesIn(Maps.asMap(context.firstMiddleLastKeys(), key -> key)); @@ -514,7 +530,9 @@ public void getAllPresent_delayed(LoadingCache cache, CacheContext con population = { Population.PARTIAL, Population.FULL }) public void getFunc_immediate(LoadingCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey(), identity()); + var value = cache.get(context.firstKey(), identity()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.get(context.lastKey(), identity())).isEqualTo(context.lastKey()); @@ -531,7 +549,9 @@ public void getFunc_immediate(LoadingCache cache, CacheContext context public void getFunc_delayed(LoadingCache cache, CacheContext context) { Function mappingFunction = context.original()::get; context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey(), mappingFunction); + var value = cache.get(context.firstKey(), mappingFunction); + assertThat(value).isNotNull(); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.get(context.lastKey(), mappingFunction)).isEqualTo(context.lastKey().negate()); @@ -568,7 +588,9 @@ public void getFunc_async(AsyncLoadingCache cache, CacheContext contex population = { Population.PARTIAL, Population.FULL }) public void get_immediate(LoadingCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.get(context.firstKey())).isEqualTo(context.firstKey()); @@ -584,7 +606,9 @@ public void get_immediate(LoadingCache cache, CacheContext context) { population = { Population.PARTIAL, Population.FULL }) public void get_delayed(LoadingCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey()); + var value = cache.get(context.firstKey()); + assertThat(value).isNotNull(); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.get(context.firstKey())).isEqualTo(context.firstKey().negate()); @@ -846,7 +870,8 @@ public void refresh(LoadingCache cache, CacheContext context) { // trigger an automatic refresh submitted = context.executor().submitted(); context.ticker().advance(2, TimeUnit.MINUTES); - cache.getIfPresent(context.absentKey()); + var value1 = cache.getIfPresent(context.absentKey()); + assertThat(value1).isEqualTo(context.absentValue()); assertThat(context.executor().submitted()).isEqualTo(submitted + 1); var automatic1 = cache.policy().refreshes().get(context.absentKey()); @@ -859,7 +884,8 @@ public void refresh(LoadingCache cache, CacheContext context) { // trigger a new automatic refresh submitted = context.executor().submitted(); context.ticker().advance(2, TimeUnit.MINUTES); - cache.getIfPresent(context.absentKey()); + var value2 = cache.getIfPresent(context.absentKey()); + assertThat(value2).isEqualTo(context.absentValue().negate()); assertThat(context.executor().submitted()).isEqualTo(submitted + 1); var automatic2 = cache.policy().refreshes().get(context.absentKey()); @@ -876,8 +902,9 @@ public void refresh(LoadingCache cache, CacheContext context) { refreshAfterWrite = Expire.ONE_MINUTE, population = Population.FULL) public void refreshes(LoadingCache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - cache.getIfPresent(context.firstKey()); + var value = cache.getIfPresent(context.firstKey()); assertThat(cache.policy().refreshes()).hasSize(1); + assertThat(value).isNotNull(); var future = cache.policy().refreshes().get(context.firstKey()); assertThat(future).isNotNull(); @@ -892,9 +919,10 @@ public void refreshes(LoadingCache cache, CacheContext context) { refreshAfterWrite = Expire.ONE_MINUTE, population = Population.FULL) public void refreshes_nullLookup(LoadingCache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - cache.getIfPresent(context.firstKey()); - var future = cache.policy().refreshes().get(context.firstKey()); + var value = cache.getIfPresent(context.firstKey()); + assertThat(value).isNotNull(); + var future = cache.policy().refreshes().get(context.firstKey()); assertThat(cache.policy().refreshes().get(null)).isNull(); assertThat(cache.policy().refreshes().containsKey(null)).isFalse(); assertThat(cache.policy().refreshes().containsValue(null)).isFalse(); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java index f6670009dc..482cf0f11b 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java @@ -61,7 +61,8 @@ public void scheduler_exception(Scheduler scheduler) { executed.set(true); throw new IllegalStateException(); }; - scheduler.schedule(executor, () -> {}, 1L, TimeUnit.NANOSECONDS); + var future = scheduler.schedule(executor, () -> {}, 1L, TimeUnit.NANOSECONDS); + assertThat(future).isNotNull(); await().untilTrue(executed); } @@ -69,7 +70,8 @@ public void scheduler_exception(Scheduler scheduler) { public void scheduler(Scheduler scheduler) { var executed = new AtomicBoolean(); Runnable task = () -> executed.set(true); - scheduler.schedule(executor, task, 1L, TimeUnit.NANOSECONDS); + var future = scheduler.schedule(executor, task, 1L, TimeUnit.NANOSECONDS); + assertThat(future).isNotNull(); await().untilTrue(executed); } @@ -99,6 +101,7 @@ public void disabledFuture_null() { /* --------------- guarded --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void guardedScheduler_null() { Scheduler.guardedScheduler(null); @@ -133,6 +136,7 @@ public void guardedScheduler_exception() { /* --------------- ScheduledExecutorService --------------- */ + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = NullPointerException.class) public void scheduledExecutorService_null() { Scheduler.forScheduledExecutorService(null); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/Stresser.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/Stresser.java index 7858956ac7..8b976a90da 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/Stresser.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/Stresser.java @@ -71,7 +71,7 @@ public void run() { execute(); } - @SuppressWarnings("FutureReturnValueIgnored") + @SuppressWarnings({"CheckReturnValue", "FutureReturnValueIgnored"}) private void initialize() { var threadFactory = new ThreadFactoryBuilder() .setPriority(Thread.MAX_PRIORITY) @@ -95,7 +95,7 @@ private void initialize() { status(); } - @SuppressWarnings("FutureReturnValueIgnored") + @SuppressWarnings({"CheckReturnValue", "FutureReturnValueIgnored"}) private void execute() { ConcurrentTestHarness.timeTasks(workload.maxThreads, () -> { int index = ThreadLocalRandom.current().nextInt(); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java index 8ca44f13f4..dd3fc5b30f 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java @@ -60,7 +60,7 @@ public void expand() { } @Test - @SuppressWarnings("ThreadPriorityCheck") + @SuppressWarnings({"CheckReturnValue", "ThreadPriorityCheck"}) public void expand_concurrent() { var buffer = new FakeBuffer(Buffer.FAILED); ConcurrentTestHarness.timeTasks(10 * NCPU, () -> { @@ -73,7 +73,7 @@ public void expand_concurrent() { } @Test(dataProvider = "buffers") - @SuppressWarnings("ThreadPriorityCheck") + @SuppressWarnings({"CheckReturnValue", "ThreadPriorityCheck"}) public void produce(FakeBuffer buffer) { ConcurrentTestHarness.timeTasks(NCPU, () -> { for (int i = 0; i < 10; i++) { @@ -85,6 +85,7 @@ public void produce(FakeBuffer buffer) { } @Test(dataProvider = "buffers") + @SuppressWarnings("CheckReturnValue") public void drain(FakeBuffer buffer) { buffer.drainTo(e -> {}); assertThat(buffer.drains).isEqualTo(0); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java index 695afb9cec..9e75073760 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java @@ -514,6 +514,7 @@ public void sentinel_ignored() { } @Test + @SuppressWarnings("CheckReturnValue") public void sentinel_unsupported() { var node = new Sentinel<>(); List methods = List.of(node::getKeyReference, node::getValueReference); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java index 347e6f0d36..93f1d649a0 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java @@ -45,7 +45,8 @@ public Iterator buffers() { public void record(ReadBuffer buffer) { ConcurrentTestHarness.timeTasks(100, () -> { for (int i = 0; i < 1000; i++) { - buffer.offer(Boolean.TRUE); + int added = buffer.offer(Boolean.TRUE); + assertThat(added).isAnyOf(ReadBuffer.SUCCESS, ReadBuffer.FAILED, ReadBuffer.FULL); Thread.yield(); } }); @@ -56,7 +57,8 @@ public void record(ReadBuffer buffer) { @Test(dataProvider = "buffers") public void drain(ReadBuffer buffer) { for (int i = 0; i < 2 * ReadBuffer.BUFFER_SIZE; i++) { - buffer.offer(Boolean.TRUE); + int added = buffer.offer(Boolean.TRUE); + assertThat(added).isAnyOf(ReadBuffer.SUCCESS, ReadBuffer.FULL); } buffer.drain(); long drained = buffer.reads(); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/HashClashTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/HashClashTest.java index 35c0392204..e4831e6a4d 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/HashClashTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/HashClashTest.java @@ -47,6 +47,7 @@ public final class HashClashTest { private static final boolean debug = false; @Test(dataProvider = "caches") + @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.ONE_FIFTY, stats = Stats.ENABLED) public void testCache(Cache cache, CacheContext context) { for (long j = 0; j < 300; ++j) { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java index bcb9149051..b8f1de4b23 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java @@ -89,7 +89,9 @@ public void after() { @SuppressWarnings("FutureReturnValueIgnored") public void readDuringCreate() { // Loaded value and waiting at expireAfterCreate (expire: infinite) - cache.get(key); + var initialValue = cache.get(key); + assertThat(initialValue).isNotNull(); + await().untilTrue(startedLoad); doLoad.set(true); await().untilTrue(startedCreate); @@ -97,7 +99,8 @@ public void readDuringCreate() { // Async read trying to wait at expireAfterRead var reader = CompletableFuture.runAsync(() -> { do { - cache.get(key); + var value = cache.get(key); + assertThat(value).isEqualTo(initialValue); } while (!endRead.get()); }, executor); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java index 6188622594..b01b791933 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java @@ -25,6 +25,7 @@ */ public final class CacheStatsTest { + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "badArgs", expectedExceptions = IllegalArgumentException.class) public void invalid(int hitCount, int missCount, int loadSuccessCount, int loadFailureCount, int totalLoadTime, int evictionCount, int evictionWeight) { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java index 17b430ad60..4351be2b15 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java @@ -66,6 +66,7 @@ import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableSet; import com.google.common.testing.FakeTicker; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * The cache configuration context for a test case. @@ -165,6 +166,7 @@ public static Map interner() { } /** Returns a thread local interned value. */ + @CanIgnoreReturnValue @SuppressWarnings("unchecked") public static T intern(T o) { return (T) interner.get().computeIfAbsent(o, identity()); @@ -275,6 +277,7 @@ private Int nextAbsentKey() { (Integer.MAX_VALUE / 2), Integer.MAX_VALUE)); } + @CanIgnoreReturnValue public long initialSize() { return (initialSize < 0) ? (initialSize = original.size()) : initialSize; } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java index bfc6f85390..fd93ee096c 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java @@ -356,18 +356,22 @@ private WithCause(RemovalCause cause) { this.cause = requireNonNull(cause); } + @CanIgnoreReturnValue public Exclusive contains(Int key, Int value) { return contains(new SimpleEntry<>(key, value)); } + @CanIgnoreReturnValue public Exclusive contains(Map map) { return contains(map.entrySet().toArray(Map.Entry[]::new)); } + @CanIgnoreReturnValue public Exclusive contains(List> entries) { return contains(entries.toArray(Map.Entry[]::new)); } + @CanIgnoreReturnValue public Exclusive contains(Entry... entries) { awaitUntil((type, listener) -> { var notifications = Stream.of(entries) diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheSubject.java index cfbdc85501..92343ec834 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheSubject.java @@ -31,6 +31,7 @@ import com.google.common.truth.FailureMetadata; import com.google.common.truth.Ordered; import com.google.common.truth.Subject; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * Propositions for {@link Cache} subjects. @@ -92,6 +93,7 @@ public void containsKey(Object key) { } /** Fails if the cache does not contain the given keys, where duplicate keys are ignored. */ + @CanIgnoreReturnValue public Ordered containsExactlyKeys(Iterable keys) { return check("containsKeys").about(map()).that(actual.asMap()).containsExactlyKeys(keys); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java index b6f156f4e1..b74fbbd0ff 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java @@ -77,6 +77,7 @@ private GuavaCacheFromContext() {} private static final ThreadLocal error = new ThreadLocal<>(); /** Returns a Guava-backed cache. */ + @SuppressWarnings("CheckReturnValue") public static Cache newGuavaCache(CacheContext context) { checkState(!context.isAsync(), "Guava caches are synchronous only"); @@ -344,6 +345,7 @@ public V computeIfAbsent(K key, Function mappingFunction } } @Override + @SuppressWarnings("CheckReturnValue") public V computeIfPresent(K key, BiFunction remappingFunction) { requireNonNull(remappingFunction); @@ -371,6 +373,7 @@ public V computeIfPresent(K key, } } @Override + @SuppressWarnings("CheckReturnValue") public V compute(K key, BiFunction remappingFunction) { requireNonNull(remappingFunction); V oldValue = get(key); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/eclipse/mutable/SumProcedure.java b/caffeine/src/test/java/com/github/benmanes/caffeine/eclipse/mutable/SumProcedure.java index d65edb54c9..4cc0ba3e6a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/eclipse/mutable/SumProcedure.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/eclipse/mutable/SumProcedure.java @@ -60,6 +60,7 @@ public Sum value(Sum argument1, T argument2) { } @Override + @SuppressWarnings("CheckReturnValue") public void value(T object) { this.sum.add(object); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/testing/ConcurrentTestHarness.java b/caffeine/src/test/java/com/github/benmanes/caffeine/testing/ConcurrentTestHarness.java index 01b3de793b..27d76efd89 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/testing/ConcurrentTestHarness.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/testing/ConcurrentTestHarness.java @@ -27,6 +27,7 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.Uninterruptibles; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * A testing harness for concurrency related executions. @@ -63,6 +64,7 @@ public static void execute(Runnable task) { * @param task the task to execute in each thread * @return the execution time for all threads to complete, in nanoseconds */ + @CanIgnoreReturnValue public static long timeTasks(int nThreads, Runnable task) { return timeTasks(nThreads, Executors.callable(task)).executionTime(); } @@ -74,6 +76,7 @@ public static long timeTasks(int nThreads, Runnable task) { * @param task the task to execute in each thread * @return the result of each task and the full execution time, in nanoseconds */ + @CanIgnoreReturnValue public static TestResult timeTasks(int nThreads, Callable task) { var startGate = new CountDownLatch(1); var endGate = new CountDownLatch(nThreads); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/testing/FutureSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/testing/FutureSubject.java index 70060d248c..d9272f94ed 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/testing/FutureSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/testing/FutureSubject.java @@ -24,6 +24,7 @@ import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; import com.google.common.truth.ThrowableSubject; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * Propositions for {@link CompletableFuture} subjects. @@ -88,6 +89,7 @@ public void succeedsWithNull() { } /** Fails if the future is did not fail with the given join() exception. */ + @CanIgnoreReturnValue public ThrowableSubject failsWith(Class clazz) { try { failWithActual("join", actual.join()); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/testing/MapSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/testing/MapSubject.java index 43ca915915..743a1103ee 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/testing/MapSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/testing/MapSubject.java @@ -25,6 +25,7 @@ import com.google.common.collect.Range; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Ordered; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * Additional propositions for {@link Map} subjects. @@ -64,6 +65,7 @@ public void hasSizeIn(Range range) { } /** Fails if the map does not contain the given keys, where duplicate keys are ignored. */ + @CanIgnoreReturnValue public Ordered containsExactlyKeys(Iterable keys) { return check("containsKeys").that(actual.keySet()) .containsExactlyElementsIn(ImmutableSet.copyOf(keys)); diff --git a/gradle/codeQuality.gradle b/gradle/codeQuality.gradle index 7444209270..c1d351bd7e 100644 --- a/gradle/codeQuality.gradle +++ b/gradle/codeQuality.gradle @@ -33,7 +33,7 @@ dependencies { // Gradle rewrites ErrorProne's dependency on Caffeine to a project dependency, which then fails. // Instead we have to download and trick the build to put the jar on the compiler's classpath. tasks.register('downloadCaffeineLocal') { - inputs.property('version', '3.1.2') + inputs.property('version', '3.1.3') def local = file(layout.buildDirectory.file('libs/caffeine-local.jar')) outputs.cacheIf { true } @@ -147,9 +147,10 @@ tasks.withType(JavaCompile).configureEach { options.forkOptions.jvmArgs += JVM_ARGS_STRONG_ENCAPSULATION options.compilerArgs << [ - '-Xlint:all,-processing,-exports', '-auxiliaryclass', + '-Xlint:all', '-processing', '-exports', '-auxiliaryclass', '-requires-automatic', '-requires-transitive-automatic', ].join(',') + options.compilerArgs += ['-Xmaxerrs', '500', '-Xmaxwarns', '500' ] options.encoding = 'UTF-8' options.errorprone { def enabledChecks = [ @@ -186,10 +187,6 @@ tasks.withType(JavaCompile).configureEach { } } -tasks.named('compileTestJava').configure { - options.errorprone.disable('NullAway') -} - tasks.withType(Test).configureEach { jvmArgs '-XX:SoftRefLRUPolicyMSPerMB=0' if (System.properties.containsKey('debug')) { diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index d45148ddba..2b67f1ddb5 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -27,7 +27,7 @@ ext { versions = [ autoValue: '1.10.1', cache2k: '2.6.1.Final', - checkerFramework: '3.30.0', + checkerFramework: '3.31.0', coherence: '22.06.2', commonsCompress: '1.22', commonsLang3: '3.12.0', @@ -44,7 +44,7 @@ ext { flipTables: '1.1.0', googleJavaFormat: '1.15.0', guava: '31.1-jre', - hazelcast: '5.2.1', + hazelcast: '5.2.2', jackrabbit: '1.48.0', jamm: '0.3.3', javaObjectLayout: '0.16', @@ -92,7 +92,7 @@ ext { bnd: '6.4.0', checkstyle: '10.7.0', coveralls: '2.12.0', - dependencyCheck: '8.0.2', + dependencyCheck: '8.1.0', errorprone: '3.0.1', findsecbugs: '1.12.0', forbiddenApis: '3.4', @@ -104,7 +104,7 @@ ext { pmd: '6.54.0', semanticVersioning: '1.1.0', snyk: '0.4', - sonarqube: '3.5.0.2730', + sonarqube: '4.0.0.2929', spotbugs: '4.7.3', spotbugsContrib: '7.4.7', spotbugsPlugin: '5.0.13', diff --git a/gradle/eclipse.gradle b/gradle/eclipse.gradle index 942ddf399d..5135fbd199 100644 --- a/gradle/eclipse.gradle +++ b/gradle/eclipse.gradle @@ -7,11 +7,14 @@ import org.gradle.plugins.ide.eclipse.model.SourceFolder apply plugin: 'eclipse' -// Exclude module-info when compiling through Eclipse -eclipse.classpath.file.whenMerged { - def main = entries.find { it instanceof SourceFolder && it.path == 'src/main/java' } - if (main != null) { - main.excludes.add('module-info.java') +// Exclude module-info and package-info when compiling through Eclipse +eclipse.classpath.file.whenMerged { + var sourceFolders = entries.findAll { it instanceof SourceFolder } + for (var sourceFolder : sourceFolders) { + sourceFolder.excludes += 'module-info.java' + if (sourceFolder.path != 'src/main/java') { + sourceFolder.excludes += '**/package-info.java' + } } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37069b4e9c..96bc8dbba0 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-rc-5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/jcache/build.gradle b/jcache/build.gradle index 0af293e2ae..37e2831da5 100644 --- a/jcache/build.gradle +++ b/jcache/build.gradle @@ -44,9 +44,6 @@ tasks.named('forbiddenApisTest').configure { tasks.named('compileJava').configure { modularity.inferModulePath = false } -tasks.named('compileTestJava').configure { - options.errorprone.disable('CheckReturnValue') -} tasks.named('jar').configure { bundle.bnd( diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java index 5dfcbc085d..d5a7592cff 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java @@ -61,7 +61,7 @@ protected CaffeineConfiguration getConfiguration() { } @Test - @SuppressWarnings({"ObjectToString", "unchecked"}) + @SuppressWarnings({"CheckReturnValue", "ObjectToString", "unchecked"}) public void getConfiguration_immutable() { var config = jcache.getConfiguration(CaffeineConfiguration.class); List modifiers = List.of( @@ -113,6 +113,7 @@ public void getConfiguration_immutable() { .isEqualTo(List.of(configuration).toString()); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void unwrap_fail() { jcache.unwrap(CaffeineConfiguration.class); @@ -126,7 +127,7 @@ public void unwrap() { .isSameInstanceAs(jcache.cache); } - @SuppressWarnings("serial") + @SuppressWarnings({"CheckReturnValue", "serial"}) @Test(expectedExceptions = IllegalArgumentException.class) public void unwrap_configuration() { abstract class Dummy implements Configuration {}; diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java index 718d10268b..2b8c801f76 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java @@ -72,6 +72,7 @@ public void illegalPath() { assertThat(TypesafeConfigurator.from(ConfigFactory.load(), "#")).isEmpty(); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalStateException.class) public void invalidCache() { TypesafeConfigurator.from(ConfigFactory.load(), "invalid-cache"); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java index 08cd70b43e..f22a20ac04 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java @@ -46,38 +46,45 @@ */ public final class JavaSerializationCopierTest { + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "nullArgs", expectedExceptions = NullPointerException.class) public void constructor_null(Set> immutableClasses, Map, Function> deepCopyStrategies) { new JavaSerializationCopier(immutableClasses, deepCopyStrategies); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "copier", expectedExceptions = NullPointerException.class) public void null_object(Copier copier) { copy(copier, null); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "copier", expectedExceptions = NullPointerException.class) public void null_classLoader(Copier copier) { copier.copy(1, null); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "copier", expectedExceptions = UncheckedIOException.class) public void serializable_fail(JavaSerializationCopier copier) { copier.serialize(new Object()); } @Test + @SuppressWarnings("CheckReturnValue") public void deserializable_resolveClass() { var copier = new JavaSerializationCopier(); copier.copy(ImmutableSet.of(), ClassLoader.getPlatformClassLoader()); } + @SuppressWarnings("CheckReturnValue") @Test(dataProvider = "copier", expectedExceptions = CacheException.class) public void deserializable_badData(JavaSerializationCopier copier) { copier.deserialize(new byte[0], Thread.currentThread().getContextClassLoader()); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = CacheException.class) public void deserializable_classNotFound() { var copier = new JavaSerializationCopier() { @@ -131,6 +138,7 @@ public void deepCopy_calendar(Copier copier) { } @Test(dataProvider = "copier") + @SuppressWarnings("CheckReturnValue") public void array_primitive(Copier copier) { int[] ints = { 0, 1, 2, 3, 4 }; assertThat(copy(copier, ints)).isEqualTo(ints); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java index 996a13a4a9..d26f8c5eef 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java @@ -46,6 +46,7 @@ public void before() throws Exception { event = new JCacheEntryEvent<>(cache, EventType.CREATED, 1, true, 2, 3); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void unwrap_fail() { event.unwrap(Map.Entry.class); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryAndMaximumSizeTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryAndMaximumSizeTest.java index d70683d172..815bd72a57 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryAndMaximumSizeTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryAndMaximumSizeTest.java @@ -87,7 +87,8 @@ public void expiry() { jcache.put(KEY_1, VALUE_2); verify(expiry).expireAfterUpdate(anyInt(), anyInt(), anyLong(), anyLong()); - jcache.get(KEY_1); + var value = jcache.get(KEY_1); + assertThat(value).isEqualTo(VALUE_2); verify(expiry).expireAfterRead(anyInt(), anyInt(), anyLong(), anyLong()); } diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryTest.java index 3d4f236c31..241fbe0233 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryTest.java @@ -15,6 +15,7 @@ */ package com.github.benmanes.caffeine.jcache.expiry; +import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.verify; @@ -67,7 +68,8 @@ public void configured() { jcache.put(KEY_1, VALUE_2); verify(expiry).expireAfterUpdate(anyInt(), anyInt(), anyLong(), anyLong()); - jcache.get(KEY_1); + var value = jcache.get(KEY_1); + assertThat(value).isEqualTo(VALUE_2); verify(expiry).expireAfterRead(anyInt(), anyInt(), anyLong(), anyLong()); } } diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheUpdateExpiryTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheUpdateExpiryTest.java index 118128a4d8..61bbd704ac 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheUpdateExpiryTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheUpdateExpiryTest.java @@ -81,7 +81,9 @@ public void getAndPut() { jcache.put(KEY_1, VALUE_1); advanceHalfExpiry(); - jcache.getAndPut(KEY_1, VALUE_1); + var value = jcache.getAndPut(KEY_1, VALUE_1); + assertThat(value).isEqualTo(VALUE_1); + Expirable expirable = getExpirable(jcache, KEY_1); assertThat(expirable.getExpireTimeMS()).isEqualTo(currentTimeMillis() + EXPIRY_DURATION); } diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java index 27f4616f6a..aa7838c55a 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java @@ -58,6 +58,7 @@ public void load_null() { } @Test(dataProvider = "throwables") + @SuppressWarnings("CheckReturnValue") public void load_failure(Throwable throwable) { try { when(cacheLoader.load(any())).thenThrow(throwable); @@ -71,6 +72,7 @@ public void load_failure(Throwable throwable) { } @Test + @SuppressWarnings("CheckReturnValue") public void load_failure_expiry() { try { when(expiry.getExpiryForCreation()).thenThrow(IllegalStateException.class); @@ -92,6 +94,7 @@ public void loadAll() { assertThat(result).containsExactly(1, -1, 2, -2, 3, -3); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = CacheLoaderException.class) public void loadAll_null() { when(cacheLoader.loadAll(anyIterable())).thenReturn(null); @@ -106,6 +109,7 @@ public void loadAll_nullMapping() { } @Test(dataProvider = "throwables") + @SuppressWarnings("CheckReturnValue") public void loadAll_failure(Throwable throwable) { try { when(cacheLoader.loadAll(any())).thenThrow(throwable); @@ -119,6 +123,7 @@ public void loadAll_failure(Throwable throwable) { } @Test + @SuppressWarnings("CheckReturnValue") public void loadAll_failure_expiry() { try { when(expiry.getExpiryForCreation()).thenThrow(IllegalStateException.class); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java index 8da88e6798..80f15cb624 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java @@ -57,6 +57,7 @@ public void unregister_error(Class throwableType) throws JM JmxRegistration.unregister(server, name); } + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = CacheException.class) public void newObjectName_malformed() { JmxRegistration.newObjectName("a=b"); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java index ec5fe4b1dd..2b511920ff 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java @@ -30,6 +30,7 @@ public final class EntryProcessorEntryTest { EntryProcessorEntry entry = new EntryProcessorEntry<>(1, 2, Optional.empty()); + @SuppressWarnings("CheckReturnValue") @Test(expectedExceptions = IllegalArgumentException.class) public void unwrap_fail() { entry.unwrap(Map.Entry.class); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java index d553b9752b..b650189269 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java @@ -74,6 +74,7 @@ protected CaffeineConfiguration getConfiguration() { } @Test + @SuppressWarnings("CheckReturnValue") public void reload() { jcache.invoke(KEY_1, this::process); assertThat(loads).isEqualTo(1); @@ -94,6 +95,7 @@ public void reload() { } @Test + @SuppressWarnings("CheckReturnValue") public void writeOccursForInitialLoadOfEntry() { map.put(KEY_1, 100); jcache.invoke(KEY_1, this::process); diff --git a/qodana.yaml b/qodana.yaml new file mode 100644 index 0000000000..760fdf97d1 --- /dev/null +++ b/qodana.yaml @@ -0,0 +1,34 @@ +version: "1.0" +profile: + name: qodana.recommended +exclude: + - name: CastCanBeRemovedNarrowingVariableType + - name: CommentedOutCode + - name: ConstantValue + - name: DataFlowIssue + - name: EmptyStatementBody + - name: EqualsWhichDoesntCheckParameterClass + - name: GrUnnecessarySemicolon + - name: GroovyEmptyStatementBody + - name: GroovyUnnecessaryReturn + - name: IgnoreResultOfCall + - name: Java9CollectionFactory + - name: JavaAnnotator + - name: JavaRequiresAutoModule + - name: NonSynchronizedMethodOverridesSynchronizedMethod + - name: NotNullFieldNotInitialized + - name: NullableProblems + - name: OptionalAssignedToNull + - name: OptionalUsedAsFieldOrParameterType + - name: RedundantCollectionOperation + - name: RedundantUnmodifiable + - name: ReplaceAssignmentWithOperatorAssignment + - name: ReturnNull + - name: SuspiciousSystemArraycopy + - name: SynchronizationOnLocalVariableOrMethodParameter + - name: SystemOutErr + - name: UnnecessaryReturn + - name: UnnecessarySemicolon + - name: UnsatisfiedRange + - name: UnstableApiUsage + - name: WhileLoopSpinsOnField diff --git a/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/admission/tinycache/HashFunctionParser.java b/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/admission/tinycache/HashFunctionParser.java index 449e4c4872..76f9e4f914 100644 --- a/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/admission/tinycache/HashFunctionParser.java +++ b/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/admission/tinycache/HashFunctionParser.java @@ -29,7 +29,7 @@ public final class HashFunctionParser { private static final byte fpMask = (byte) 255; // (all bits in byte are 1, (logical value of -1)); private static final long chainMask = 63L; // (6 first bit are set to 1). private static final long m = 0xc6a4a7935bd1e995L; - private static final long Seed64 = 0xe17a1465; + private static final long Seed64 = 0xe17a1465L; private static final int r = 47; public final HashedItem fpaux; // used just to avoid allocating new memory as a return value.