弱引用有实际用途吗? [英] Is there a practical use for weak references?

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

问题描述

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

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

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.

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

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