I’m very curious about how this thing works inside Android. I have a class with two List<> inside, instantiated at runtime and loaded with objects created while reading some data, I want to know what happens with those Lists in this situation:
-
Class A has List B and List C with many other initialized objects
inside. -
Another different class get a reference of List C from a
method of Class A, likepublic List<myObject> GetList(). -
Somewhere in code, Class A is no longer used and application
signals that to garbage collector, setting object to null.
What happens with my List C that is referenced by other object? What happens with Object class A?
I’ve tried to track garbage collector with Logcat running apk in debugger step-by-step but no luck at all. Sometimes it frees memory, sometimes not, I couldn’t pinpoint any specific behaviour.
If there is any object, that still has a path to root, containing a reference to another object, the referenced object will not be garbage collected. So if you create object A, that has a sub object A1. Then create object B and through what ever means pass a reference to A1 to object B. Even when object A is GC’d A1 will not be because object B still holds a reference. (In your example, A & B will be gc’d… C will not)
You can experiment with the mechanics behind garbage collection by telling the system explicitly to perform a collection at certain times with a
System.gc();call. Also you can override the finalize in object to see exactly when the given object is collected.:You can learn a lot through experimenting with objects, references, finalize and explicit calls for gc(). I would remove the overridden finalize call when you done testing.