如何强制 JVM 清除 WeakHashMap 的所有 WeakReferences/键
有没有办法强制 jvm 清除所有 WeakReferences
(或 WeakHashMap
的所有键)(如果它们不再被常规引用引用)?
触发垃圾收集将不起作用,弱引用仍然存在。 (我读到弱引用只有在内存不足时才会被清除)。
Is there a way to force the jvm that it should clear all WeakReferences
(or all keys of a WeakHashMap
) if they aren't referenced by regular references anymore?
Triggering a garbage collection will not work, the weak references remain alive.
(I read that weak references will only be cleared if the memory is low).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当内存不足时,软引用将被清除。
弱引用被更频繁地清除(就像对象只剩下弱引用时一样)
查看包的官方 Java 文档(包文档对于解释很有用):
http://download.oracle .com/javase/1.5.0/docs/api/java/lang/ref/package-summary.html
您能否引用在关闭时从 Tomcat 看到的确切消息?你确定你没有误解它吗?对于 Tomcat 来说,重要的是没有硬引用为 ServletContext 固定 ClassLoader。
关于 WeakHashMap: http://download.oracle。 com/javase/1.5.0/docs/api/java/util/WeakHashMap.html
只有按键被弱握。你用什么作为“价值”?该值是否强烈地自我引用自己的“密钥”?借此,我质疑您对 WeakHashMap 为您提供什么的理解(假设它是完成这项工作的正确工具)。
根据我的经验,您可以在第一次 GC 扫描时使用 System.gc() 100% 可靠地清除 Sun JVM 5 的弱引用。但他们并不能保证这一点。
SoftReferences are cleared when memory is low.
WeakReferences are cleared more often (like all the time when an object only has weak references left)
Check out the offcial Java doc for the package (the package documentation is useful to explain):
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ref/package-summary.html
Can you quote the exact message you are seeing from Tomcat on shutdown ? are you sure you are not misinterpreting it ? What is important for Tomcat is that there are no hard-references that are pinning the ClassLoader for the ServletContext.
Re WeakHashMap: http://download.oracle.com/javase/1.5.0/docs/api/java/util/WeakHashMap.html
Only the keys are Weakly held. What are you using as the "value" ? does the value self-reference its own "key" strongly ? With this I am questioning your understanding of what a WeakHashMap is providing for you (this presumes it is the correct tool for the job).
In my experience you can get the WeakReferences with Sun JVM 5 to be cleared with System.gc() 100% reliable for me on the first GC sweep. But they don't guarantee that point.