javaandroidgarbage-collectionweak-referencesstrong-references

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. And my predecessor used the weak reference (as instance variables) to storing views in the holder for the RecyclerView's adapter. I want to know why he did that. I had an idea that can be weak reference forced GC to collect the object. 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. This can be so?


Solution

  • 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.

    Beyond that: you can't distinguish your two cases in many cases.

    Meaning: if you use a weak reference for 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.