Matthieu
Matthieu

Reputation: 3097

Prioritize objects for GC

I'm implementing an image cache that can will be heavy on memory usage so I'm keeping a SoftReference to image data so the GC can collect them under memory pressure.

However, each entry has an age so is there a way to tell a GC (which one?) to collect older entries instead of "random" ones?

I guess I could kind of do it myself by keeping strong references and removing entries on low freeMemory(), but that's kind of an "indirect free" (GC still has to kick-in to actually free the memory).

Upvotes: 2

Views: 69

Answers (1)

Erik
Erik

Reputation: 2051

From the docs:

All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError. Otherwise no constraints are placed upon the time at which a soft reference will be cleared or the order in which a set of such references to different objects will be cleared. Virtual machine implementations are, however, encouraged to bias against clearing recently-created or recently-used soft references.

Thus a sophisticated cache can, for example, prevent its most recently used entries from being discarded by keeping strong referents to those entries, leaving the remaining entries to be discarded at the discretion of the garbage collector.

This is from the JDK 11 java docs. In short, the answer is NO. I guess you could try to do crazy stuff with finalize but I would recommend against it. Your idea of using strong references might be the most viable.

Upvotes: 2

Related Questions