使用WeakHashMap减少内存使用量 [英] Reduce Memory Usage With WeakHashMap

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

问题描述

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


WeakHashMap中的每个关键对象间接存储为
,作为
的引用因此只有在
后,
的一个键才会被自动收集器清除
,并且被
清除。


然后


请注意,一个值对象可以通过
WeakHashMap本身将
间接引用到它的键上;也就是说,值
对象可能强烈地引用某个
其他键对象,其相关联的
值对象又强烈地将
引用到第一个值对象的键。 / p>

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

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

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

Java中是否有可能?



谢谢。

解决方案

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

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



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


In the Javadoc of WeakHashMap.html, it said

"Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector."

And then

Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object.

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减少内存使用量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆