开发者

How to force the JVM to clear all WeakReferences / keys of a WeakHashMap

开发者 https://www.devze.com 2023-04-12 08:30 出处:网络
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?

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 wea开发者_高级运维k references will only be cleared if the memory is low).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消