0

What is the order that garbage collection collects references in this case:

Activity -> Button -> Anonymous class for onClickListener.

How all this is garbage collected when onClickListener holds reference to the wrapping class (Activity)?

Teodor
  • 300
  • 1
  • 13

1 Answers1

1

If you're never passing your Button or listener outside the Activity, then this does not effect the GC process at all. They will all get garbage collected when the Activity is no longer referenced anywhere.

wsanville
  • 37,158
  • 8
  • 76
  • 101
  • Yes I know that, Im asking how it's working and why it is working that way.Please try to explain that. – Teodor Dec 12 '12 at 19:12
  • 1
    Try to imagine all of these object references as a directed graph. Objects in your entire Android application can also be represented this way too. If the GC process discovers that any object is totally disconnected from the graph, or an entire section of the graph is disconnected, it is eligible for garbage collection. – wsanville Dec 12 '12 at 19:15
  • Okay, I see. Why then singletons aren't garbage collected? – Teodor Dec 12 '12 at 19:20
  • Singletons are typically implemented as `static` variables, and `static` variables aren't really eligible for collection. See [this question](http://stackoverflow.com/questions/453023/are-static-fields-open-for-garbage-collection) for more info. – wsanville Dec 12 '12 at 19:27
  • If the static variables used in a singleton are not declared final, then you can set them to null if you are finished with a singleton; which will allow the referenced objects to be collected. However, a better idea would be probably not to use a singleton at all; as their weird undeterministic behavior of their initializations make them hard to test and unpredictable in a multithreaded application (even when you synchronize them). – SylvainL Dec 13 '12 at 09:54