在 WeakHashMap.html 的 Javadoc 中,它说
"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."
然后
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.
但是WeakHashMap中Key和Value不应该都使用弱引用吗? 即,如果内存不足,GC 将释放值对象所持有的内存(因为在大多数情况下,值对象很可能比键对象占用更多的内存)?
如果 GC 释放了 Value 对象,Key 对象也可以释放吗?
基本上,我正在寻找一个 HashMap,它可以在内存不足时减少内存使用(如果需要,GC 会收集值和键对象)。
Java 中可以吗?
谢谢。
最佳答案
弱引用不适合缓存 - NetBeans 做到了,但可能会变得愚蠢。
SoftReference
就是您想要的。实际上很难做到正确 - 所以复制别人的解决方案。有些人建议您自己显式管理缓存。
引用
仅适用于单个引用。有人提议向 Java SE 添加“ephemerons”,但我还没有看到任何具体实现。
关于java - 使用 WeakHashMap 减少内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2473410/