Javadocs 说“当一个键被丢弃时,它的条目就会有效从地图中删除”。
但除非有另一个线程偶尔删除此类 Map.Entry
条目,否则值对象不会被映射强引用吗?但由于没有这样的线程在运行,因此只有 get
方法调用可以删除此类条目 - 一次一个。
由于这个原因,我几乎总是使用 WeakHashMap>
。为什么他们不将其作为默认行为 - 值也作为弱引用?
Javadocs says "When a key has been discarded its entry is effectively removed from the map".
But unless there is another thread that occasionally removes such Map.Entry
entries, won't the value objects be strongly referenced by the map? But since there is no such thread running, only the get
method invocations can remove such entries - one at a time.
I almost always use WeakHashMap<K, WeakReference<V>>
for that reason. Why would they not have made that the default behavior - values as weak references too?
发布评论
评论(1)
引用队列用于自动删除条目。
http://docs.oracle.com /javase/1.4.2/docs/api/java/lang/ref/ReferenceQueue.html
基本上,弱引用是垃圾收集器的核心部分,因此当发生 GC 扫描时,会找到未使用的引用并将其放入队列中,然后可以根据这些队列的内容采取操作。
线程可以位于队列的
remove
方法在需要完成清理或轮询
队列时发出警报。“Java 理论与实践:用弱引用堵塞内存泄漏” 解释:
编辑:
即使使用队列,弱映射仍然可能泄漏。 Ephemerons 试图解决弱密钥引用强保留值(该值引用该密钥)的情况。它们无法在 java 中实现。
Reference queues are used to automatically remove entries.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ref/ReferenceQueue.html
Basically, weak references are a core part of the garbage collector, so when a GC sweep happens, unused references are found and put onto queues and then action can be taken based on the content of those queues.
A thread can sit on the queue's
remove
method to be alerted when cleanup needs to be done orpoll
the queue."Java theory and practice: Plugging memory leaks with weak references" explains:
EDIT:
Even with queues, weak maps can still leak. Ephemerons are an attempt to solve the case where a weak key references a strongly held value that references the key. They are not implementable in java.