Is there a practical use for weak references?(弱引用有实际用途吗?)
问题描述
可能重复:
弱引用 - 它们有多大用处?
既然垃圾收集器可以随时声明弱引用,那么使用它们有什么实际理由吗?
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.
这篇关于弱引用有实际用途吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:弱引用有实际用途吗?


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01