|
27 | 27 | import junit.framework.TestCase; |
28 | 28 |
|
29 | 29 | import com.github.benmanes.caffeine.cache.Caffeine; |
| 30 | +import com.github.benmanes.caffeine.cache.Weigher; |
30 | 31 | import com.github.benmanes.caffeine.guava.CaffeinatedGuava; |
31 | 32 | import com.google.common.cache.CacheTesting.Receiver; |
32 | 33 | import com.google.common.cache.LocalCache.ReferenceEntry; |
@@ -104,6 +105,56 @@ public void testEviction_maxWeight() { |
104 | 105 | CacheTesting.checkValidState(cache); |
105 | 106 | } |
106 | 107 |
|
| 108 | + /** |
| 109 | + * With an unlimited-size cache with maxWeight of 0, entries weighing 0 should still be cached. |
| 110 | + * Entries with positive weight should not be cached (nor dump existing cache). |
| 111 | + */ |
| 112 | + public void testEviction_maxWeight_zero() { |
| 113 | + CountingRemovalListener<Integer, Integer> removalListener = countingRemovalListener(); |
| 114 | + IdentityLoader<Integer> loader = identityLoader(); |
| 115 | + |
| 116 | + // Even numbers are free, odd are too expensive |
| 117 | + Weigher<Integer, Integer> evensOnly = (k, v) -> k % 2; |
| 118 | + |
| 119 | + LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() |
| 120 | + .maximumWeight(0) |
| 121 | + .weigher(evensOnly) |
| 122 | + .removalListener(removalListener), |
| 123 | + loader); |
| 124 | + |
| 125 | + // 1 won't be cached |
| 126 | + assertThat(cache.getUnchecked(1)).isEqualTo(1); |
| 127 | + assertThat(cache.asMap().keySet()).isEmpty(); |
| 128 | + |
| 129 | + cache.cleanUp(); |
| 130 | + assertThat(removalListener.getCount()).isEqualTo(1); |
| 131 | + |
| 132 | + // 2 will be cached |
| 133 | + assertThat(cache.getUnchecked(2)).isEqualTo(2); |
| 134 | + assertThat(cache.asMap().keySet()).containsExactly(2); |
| 135 | + |
| 136 | + cache.cleanUp(); |
| 137 | + CacheTesting.checkValidState(cache); |
| 138 | + assertThat(removalListener.getCount()).isEqualTo(1); |
| 139 | + |
| 140 | + // 4 will be cached |
| 141 | + assertThat(cache.getUnchecked(4)).isEqualTo(4); |
| 142 | + assertThat(cache.asMap().keySet()).containsExactly(2, 4); |
| 143 | + |
| 144 | + cache.cleanUp(); |
| 145 | + assertThat(removalListener.getCount()).isEqualTo(1); |
| 146 | + |
| 147 | + // 5 won't be cached, won't dump cache |
| 148 | + assertThat(cache.getUnchecked(5)).isEqualTo(5); |
| 149 | + assertThat(cache.asMap().keySet()).containsExactly(2, 4); |
| 150 | + |
| 151 | + cache.cleanUp(); |
| 152 | + assertThat(removalListener.getCount()).isEqualTo(2); |
| 153 | + |
| 154 | + // Should we pepper more of these calls throughout the above? Where? |
| 155 | + CacheTesting.checkValidState(cache); |
| 156 | + } |
| 157 | + |
107 | 158 | public void testEviction_overflow() { |
108 | 159 | CountingRemovalListener<Object, Object> removalListener = countingRemovalListener(); |
109 | 160 | IdentityLoader<Object> loader = identityLoader(); |
|
0 commit comments