gpt4 book ai didi

java - 为 GC 优先处理对象

转载 作者:行者123 更新时间:2023-12-04 08:33:35 25 4
gpt4 key购买 nike

我正在实现一个可能会占用大量内存的图像缓存,因此我保留了 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 做一些疯狂的事情但我会建议反对它。
您使用强引用的想法可能是最可行的。

关于java - 为 GC 优先处理对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64910231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com