简体   繁体   English

Java WeakReference 是否与 swift 弱关键字相同?

[英]Is Java WeakReference the same as the swift weak keyword?

I know there is a similar question has been answered in this post .我知道这篇文章中已经回答了一个类似的问题。 However, I am still confused about whether java has the retain cycle problem as java also has the WeakReference class.但是,我仍然对 java 是否存在保留周期问题感到困惑,因为 java 也有 WeakReference class。 So, are they serving the same purpose?那么,它们的目的是否相同? What the difference between two of them?他们两个有什么区别?

Java does not have the "retain cycle problem". Java 不存在“保留周期问题”。

This problem exists for systems that use reference counting, which the Java GC does not use.使用引用计数的系统存在此问题,Java GC 不使用该计数。

Therefore in Java the WeakReference class has nothing to do with those.因此在 Java 中, WeakReference class 与这些无关。 It's simply a way to hold on to a reference to something while also not preventing it from being garbage collected这只是一种保持对某事物的引用同时也不会阻止它被垃圾收集的方法

In other words, you can use it to remember an object as long as something else (strongly) references it.换句话说,只要其他东西(强烈)引用它,您就可以用它来记住 object。

This functionality is quite similar to what the weak keyword does in Swift.此功能与 Swift 中的weak关键字的功能非常相似。 However, as described above, reference cycles don't stop objects from being collected in Java, so WeakReference is not needed in this specific case.但是,如上所述,引用循环不会阻止在 Java 中收集对象,因此在这种特定情况下不需要WeakReference

This SO question lists some practical uses for weak references and this question discusses uses specifically in an Java/Android environment. 这个 SO question列出了弱引用的一些实际用途, 这个问题专门讨论了在 Java/Android 环境中的用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM