简体   繁体   English

弱,强引用和垃圾回收

[英]Weak, strong references and garbage collection

I have two situations: 我有两种情况:

  1. When an object (has only strong refs) loses all of its strong references, it becomes available for garbage collection. 当一个对象(只有强引用)失去所有强引用时,就可以用于垃圾回收。
  2. When the object has only weak references, it also becomes available for garbage collection. 当对象只有弱引用时,它也可用于垃圾回收。

In what situation the object will be collected faster? 在什么情况下可以更快地收集物体? Or there is no difference? 还是没有区别?

I'm working on the old android application. 我正在使用旧的android应用程序。 And my predecessor used the weak reference (as instance variables) to storing views in the holder for the RecyclerView's adapter. 我的前任使用弱引用(作为实例变量)将视图存储在RecyclerView适配器的支架中。 I want to know why he did that. 我想知道他为什么这样做。 I had an idea that can be weak reference forced GC to collect the object. 我有一个想法,可以弱引用强制GC收集对象。 I mean that in the next garbage collection the object with only weak references to 100% will be collected when object without references maybe not. 我的意思是,在下一个垃圾回收中,当没有引用的对象可能不被引用时,将仅收集具有100%弱引用的对象。 This can be so? 这样可以吗?

Why would that matter? 为什么会这样呢?

The point is: the garbage collector starts collecting eligible objects ... when it "thinks" it is required to do that. 关键是:垃圾收集器开始收集合格的对象……当它“思考”时,需要这样做。 In other words: it doesn't matter when your objects become eligible; 换句话说:对象何时符合资格并不重要; what matters is that they are eligible when the GC starts collecting. 重要的是, GC开始收集 ,它们才有资格。

Beyond that: you can't distinguish your two cases in many cases. 除此之外:在很多情况下您无法区分这两种情况。

Meaning: if you use a weak reference for X; 含义:如果对X使用弱引用; that still means that other "strong" references might exist. 这仍然意味着可能存在其他“强”引用。 The object only becomes eligible when those strong references go away. 仅当那些引用消失时,该对象才有资格。

The key point is: only eligible objects will be collected. 关键点是:仅收集合格的对象。 Their history that leads to make them eligible does not matter at all. 他们的历史使他们有资格没有任何关系。

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

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