Search code examples
javaandroidcollectionsfragmentgarbage

Garbage collection of a fragment in java


This may be a stupid question but i have little knowledge of garbage collection. When i looked up info about it, it became clear that nullifying an object sets it's reference count to 0 so it becomes eligble for garbage collection

So i wanted to test it and I made a fragment,it uses about 5 MB of memory. When i remove the fragment with the transactionmanager, nullify the fragment and explicitly call the garbage collector (GC.collect()),the allocated memory stays the same and i don't get the 5 MB back..

What could be the reason(s) for this?

public void Unselect()
    {
        var ft = this.SupportFragmentManager.BeginTransaction ();

        switch (selected)
        {

        case 8:...
        case 9:
            //FindViewById (Resource.Id.fragment_container).SetBackgroundDrawable (null);
            ft.Hide (carFragment);
            ft.Remove (carFragment);
            Console.WriteLine ("NULLIFY");
            carFragment = null;
            break;
        case 10:...
        }

        ft.Commit ();

The carFragment is a fragment that has a Google Maps V2 supportfragment in it


Solution

  • There are at least two reasons:

    1. You can suggest a garbage collection using System.gc(). That does not force a gc, it just suggests it. It turns out that, in Android VMs, it usually does cause a gc
    2. More important, a Fragment is a managed object! You have no way of knowing whether you've removed all of the container's references. Until they are all gone, a GC will not collect the object.