android garbage collector, freeing objects inside

2019-08-04 09:40发布

问题:

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:

  1. Class A has List B and List C with many other initialized objects inside.

  2. Another different class get a reference of List C from a method of Class A, like public List<myObject> GetList().

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

回答1:

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

   @Override
   protected void finalize() throws Throwable {
      try {
         Log.d("Learning about GC", "My Object has been GC'd." + this);         
      } finally {
         super.finalize();
      }
   }

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.



回答2:

The object of class A will be garbage collected during the next GC-cycle. List B will be GC'ed too. And List C will not be GC'ed because it can be reached from GC roots.



回答3:

By default java creates an object by reference instead of by value. So, in this case if the garbage collector would pick up and empty all A B C and the then the other class that referenced C would be empty, since it didnt create a duplication of the class, it just referenced it.