@@ -232,7 +232,7 @@ private V computeAsync(K key, IOFunction<? super K, ? extends V> mappingFunction
232232 // We reserved the slot, so we do the work
233233 V value = mappingFunction .apply (key );
234234 future .complete (value ); // This will update the weight and expiration
235- recordRamBytes (key , null , value );
235+ recordRamBytes (key , value );
236236 inserts .increment ();
237237 return value ;
238238 } catch (Error | RuntimeException | IOException e ) {
@@ -262,7 +262,7 @@ public V computeIfAbsent(K key, IOFunction<? super K, ? extends V> mappingFuncti
262262 if (value == null ) {
263263 return null ;
264264 }
265- recordRamBytes (key , null , value );
265+ recordRamBytes (key , value );
266266 inserts .increment ();
267267 return value ;
268268 });
@@ -275,30 +275,34 @@ public V computeIfAbsent(K key, IOFunction<? super K, ? extends V> mappingFuncti
275275 public V put (K key , V val ) {
276276 inserts .increment ();
277277 V old = cache .asMap ().put (key , val );
278- recordRamBytes (key , old , val );
278+ // ramBytes decrement for `old` happens via #onRemoval
279+ if (val != old ) {
280+ // NOTE: this is conditional on `val != old` in order to work around a
281+ // behavior in the Caffeine library: where there is reference equality
282+ // between `val` and `old`, caffeine does _not_ invoke RemovalListener,
283+ // so the entry is not decremented for the replaced value (hence we
284+ // don't need to increment ram bytes for the entry either).
285+ recordRamBytes (key , val );
286+ }
279287 return old ;
280288 }
281289
282290 /**
283- * Update the estimate of used memory
291+ * Update the estimate of used memory.
292+ *
293+ * <p>NOTE: old value (in the event of replacement) adjusts {@link #ramBytes} via {@link
294+ * #onRemoval(Object, Object, RemovalCause)}
284295 *
285296 * @param key the cache key
286- * @param oldValue the old cached value to decrement estimate (can be null)
287297 * @param newValue the new cached value to increment estimate
288298 */
289- private void recordRamBytes (K key , V oldValue , V newValue ) {
299+ private void recordRamBytes (K key , V newValue ) {
290300 ramBytes .add (
291301 RamUsageEstimator .sizeOfObject (newValue , RamUsageEstimator .QUERY_DEFAULT_RAM_BYTES_USED ));
292- if (oldValue == null ) {
293- ramBytes .add (
294- RamUsageEstimator .sizeOfObject (key , RamUsageEstimator .QUERY_DEFAULT_RAM_BYTES_USED ));
295- ramBytes .add (RamUsageEstimator .LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY );
296- if (async ) ramBytes .add (RAM_BYTES_PER_FUTURE );
297- } else {
298- ramBytes .add (
299- -RamUsageEstimator .sizeOfObject (
300- oldValue , RamUsageEstimator .QUERY_DEFAULT_RAM_BYTES_USED ));
301- }
302+ ramBytes .add (
303+ RamUsageEstimator .sizeOfObject (key , RamUsageEstimator .QUERY_DEFAULT_RAM_BYTES_USED ));
304+ ramBytes .add (RamUsageEstimator .LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY );
305+ if (async ) ramBytes .add (RAM_BYTES_PER_FUTURE );
302306 }
303307
304308 @ Override
0 commit comments