diff --git a/guava/src/test/java/com/google/common/cache/CacheEvictionTest.java b/guava/src/test/java/com/google/common/cache/CacheEvictionTest.java index 8e84aa1c97..af8f89fa04 100644 --- a/guava/src/test/java/com/google/common/cache/CacheEvictionTest.java +++ b/guava/src/test/java/com/google/common/cache/CacheEvictionTest.java @@ -27,6 +27,7 @@ import junit.framework.TestCase; import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.Weigher; import com.github.benmanes.caffeine.guava.CaffeinatedGuava; import com.google.common.cache.CacheTesting.Receiver; import com.google.common.cache.LocalCache.ReferenceEntry; @@ -104,6 +105,56 @@ public void testEviction_maxWeight() { CacheTesting.checkValidState(cache); } + /** + * With an unlimited-size cache with maxWeight of 0, entries weighing 0 should still be cached. + * Entries with positive weight should not be cached (nor dump existing cache). + */ + public void testEviction_maxWeight_zero() { + CountingRemovalListener removalListener = countingRemovalListener(); + IdentityLoader loader = identityLoader(); + + // Even numbers are free, odd are too expensive + Weigher evensOnly = (k, v) -> k % 2; + + LoadingCache cache = CaffeinatedGuava.build(Caffeine.newBuilder() + .maximumWeight(0) + .weigher(evensOnly) + .removalListener(removalListener), + loader); + + // 1 won't be cached + assertThat(cache.getUnchecked(1)).isEqualTo(1); + assertThat(cache.asMap().keySet()).isEmpty(); + + cache.cleanUp(); + assertThat(removalListener.getCount()).isEqualTo(1); + + // 2 will be cached + assertThat(cache.getUnchecked(2)).isEqualTo(2); + assertThat(cache.asMap().keySet()).containsExactly(2); + + cache.cleanUp(); + CacheTesting.checkValidState(cache); + assertThat(removalListener.getCount()).isEqualTo(1); + + // 4 will be cached + assertThat(cache.getUnchecked(4)).isEqualTo(4); + assertThat(cache.asMap().keySet()).containsExactly(2, 4); + + cache.cleanUp(); + assertThat(removalListener.getCount()).isEqualTo(1); + + // 5 won't be cached, won't dump cache + assertThat(cache.getUnchecked(5)).isEqualTo(5); + assertThat(cache.asMap().keySet()).containsExactly(2, 4); + + cache.cleanUp(); + assertThat(removalListener.getCount()).isEqualTo(2); + + // Should we pepper more of these calls throughout the above? Where? + CacheTesting.checkValidState(cache); + } + public void testEviction_overflow() { CountingRemovalListener removalListener = countingRemovalListener(); IdentityLoader loader = identityLoader();