Video in progress

A team wants to write a "self-cleaning" cache based on SoftReference. How do you evaluate that idea, and what do you suggest instead?

SoftReferences hand the cache policy to the GC: they are cleared only under heap pressure and in an unpredictable way. As a result the heap stays full all the time and the GC gets heavier. A size-bounded cache (Caffeine) or an external cache is better.

📖 Answer

In theory it is elegant: "we keep things if memory allows, and if not, the GC clears them itself". In practice this is what happens:

  • HotSpot clears a soft reference based on its last use time and the amount of free heap (SoftRefLRUPolicyMSPerMB). That means the cache fills the heap almost completely.
  • Because the heap is always full, the GC runs often and heavily, and the metrics show a picture that looks like a "leak".
  • When pressure arrives, the cache loses a large part at once, exactly when the load is at its highest. Then all the requests hit the DB (a cache stampede).
  • Every reference object is extra work for the GC.

The solution I suggest is a cache with an explicit policy:

Cache<Long, Product> cache = Caffeine.newBuilder()
    .maximumWeight(200_000_000)                 // approximate bytes
    .weigher((Long k, Product p) -> p.estimatedSize())
    .expireAfterWrite(Duration.ofMinutes(10))
    .recordStats()
    .build();

Here the memory budget, the TTL and the hit rate are in front of you, and you control them yourself.

The next question is whether the cache has to be inside the JVM at all. If the size is a few GB, or several instances need to see the same data, an external cache like Redis keeps the heap small and the GC light. The cost is a network call and serialization. A two-level setup often works: a small local Caffeine + a shared Redis. I accept SoftReference in only one case: small helper structures where recomputing is very cheap and heap pressure is never expected.