对于弱引用有实际用途吗

对于弱引用有实际用途吗

本文介绍了对于弱引用有实际用途吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于弱引用可以被垃圾回收器在任何时候,是否有任何使用它们的实际原因?

解决方案

如果你想保留对某些东西的引用只要它在其他地方使用,例如一个Listener,你可以使用一个弱引用。

WeakHashMap可以用来作为派生数据的密钥的短暂缓存。它也可以用来保存关于其他对象的信息,并且你不知道这些对象何时被丢弃。



BTW软引用就像弱引用,但它们并不总是立即清理干净。 GC可以随时丢弃弱引用,并且可以保留软引用。



还有一种叫做Phantom Reference的引用。这用于GC清理过程,并指向一个对象,因为它正在清理过程中,因此它不能被普通代码访问。


Since weak references can be claimed by the garbage collector at any time, is there any practical reason for using them?

解决方案

If you want to keep a reference to something as long as it is used elsewhere e.g. a Listener, you can use a weak reference.

WeakHashMap can be used as a short lived cache of keys to derived data. It can also be used to keep information about objects used else where and you don't know when those objects are discarded.

BTW Soft References are like Weak references, but they will not always be cleaned up immediately. The GC will always discard weak references when it can and retain Soft References when it can.

There is another kind of reference called a Phantom Reference. This is used in the GC clean up process and refers to an object which isn't accessible to "normal" code because its in the process of being cleaned up.

这篇关于对于弱引用有实际用途吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:18