使用WeakHashMap减少内存使用量

使用WeakHashMap减少内存使用量

本文介绍了使用WeakHashMap减少内存使用量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WeakHashMap.html的Javadoc中, a>,它表示

然后

但是WeakHashMap中不应该使用Key和Value两个弱引用吗?
也就是说,如果内存不足,GC将释放值对象所拥有的内存(因为在大多数情况下,值对象最有可能占用比内存大的内存)?

如果GC释放Value对象,那么Key对象也可以是自由的?

基本上,我正在寻找一个HashMap来减少内存(如果需要的话,GC会收集值和关键对象)。

Java中是否有可能?



谢谢。

解决方案

弱引用对缓存不适用 - NetBeans可以做到这一点, p>

SoftReference 就是你想要的。实际上很难做到 - 因此请复制别人的解决方案。有些人建议您自己明确管理缓存。



参考仅适用于单个参考。有人建议在Java SE中增加ephemerons,但是我还没有看到一个实现可以随时随地实现。


In the Javadoc of WeakHashMap.html, it said

And then

But should not both Key and Value should be used weak reference in WeakHashMap?i.e. if there is low on memory, GC will free the memory held by the value object (since the value object most likely take up more memory than key object in most cases)?

And if GC free the Value object, the Key Object can be free as well?

Basically, I am looking for a HashMap which will reduce memory usage when there is low memory (GC collects the value and key objects if necessary).

Is it possible in Java?

Thank you.

解决方案

Weak references are inappropriate for caches - NetBeans does it, and can go silly.

SoftReference is what you want. It's actually quite difficult to get it right - so copy somebody else's solution. Some people advise explicitly managing caches yourself.

References only work with a single reference. There was a proposal for adding "ephemerons" to Java SE, but I haven't seen an implementation go anywhere with that.

这篇关于使用WeakHashMap减少内存使用量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:09