为 GC 确定对象的优先级
Prioritize objects for GC
我正在实施一个可能会占用大量内存的图像缓存,因此我保留了一个 SoftReference
图像数据,以便 GC 可以在内存压力下收集它们。
但是,每个条目都有一个年龄,所以有没有办法告诉 GC(哪个?)收集旧条目而不是“随机”条目?
我想我可以通过保持强引用并删除低 freeMemory()
条目来自己做,但这是一种“间接释放”(GC 仍然必须启动才能真正释放内存)。
来自文档:
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.
这来自 JDK 11 java 文档。简而言之,答案是否定的。我想你可以尝试用 finalize
做一些疯狂的事情,但我不建议这样做。
您使用强引用的想法可能是最可行的。
我正在实施一个可能会占用大量内存的图像缓存,因此我保留了一个 SoftReference
图像数据,以便 GC 可以在内存压力下收集它们。
但是,每个条目都有一个年龄,所以有没有办法告诉 GC(哪个?)收集旧条目而不是“随机”条目?
我想我可以通过保持强引用并删除低 freeMemory()
条目来自己做,但这是一种“间接释放”(GC 仍然必须启动才能真正释放内存)。
来自文档:
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.
这来自 JDK 11 java 文档。简而言之,答案是否定的。我想你可以尝试用 finalize
做一些疯狂的事情,但我不建议这样做。
您使用强引用的想法可能是最可行的。