弱引用有实际用途吗?

可能重复:
弱引用 - 它们有多大用处?

既然垃圾收集器可以随时声明弱引用,那么使用它们有什么实际理由吗?

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 可用作派生数据的键的短暂缓存.它还可以用于保存有关在其他地方使用的对象的信息,并且您不知道这些对象何时被丢弃.

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.

顺便说一句,软引用类似于弱引用,但它们并不总是会立即被清除.GC 总是会在可能的情况下丢弃弱引用,并在可能的情况下保留软引用.

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.

还有另一种引用,称为幻影引用.这在 GC 清理过程中使用,指的是正常"代码无法访问的对象,因为它正在清理过程中.

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.

相关文章