You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Guava Cache:cleanUp与invalidateAll选型及cleanUp作用问询

Guava Cache: invalidateAll vs cleanUp for Memory Release

Great question—this is a common point of confusion since Guava's official docs don’t explicitly spell out the memory implications of these two methods. Let’s break this down clearly:

Which method should you use to release heap memory used by cache objects?

You’re spot-on with your source code observation: invalidateAll() is the correct choice here.

When you call invalidateAll() (either the no-arg version or the one targeting specific keys), Guava Cache’s underlying LocalCache (and its segmented structures) will explicitly set the corresponding cache entry references to null. This removes the strong references holding onto your cached objects, allowing the JVM’s garbage collector to fully reclaim their heap memory.

This method is purpose-built to clear the cache (or a subset of entries) and free up associated memory—exactly what you need when your goal is to release cached object memory.

What’s the actual purpose of cleanUp()?

cleanUp() is not meant to actively release memory by removing valid cache entries. Instead, it handles background maintenance tasks to keep the cache’s internal state healthy. Here’s what it does:

  • Cleans up cache entries that have expired (per expireAfterWrite or expireAfterAccess policies) but haven’t been automatically removed yet.
  • Removes entries where the key or value has been garbage-collected (if you’re using weak/soft references via CacheBuilder.weakKeys(), weakValues(), or softValues()).
  • Performs internal housekeeping like tidying up hash table collisions or resizing segments if needed.

Guava Cache typically runs these cleanup tasks automatically during normal read/write operations. You’d only need to call cleanUp() manually if you know there are a large number of expired or GC’d entries sitting around, and you want to clean them up immediately instead of waiting for the automatic triggers.

In short: cleanUp() keeps the cache tidy, but it won’t free up memory from valid, unexpired cache objects.


内容的提问来源于stack exchange,提问作者LppEdd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:20:25