弱引用有实际用途吗?

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)