2

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

DennisVA
  • 2,068
  • 1
  • 25
  • 35
  • 3
    `nullifying an object sets it's reference count to 0`. No. It decrements the counter because this reference does no longer exist, but there can be other references retaining the object. Also in your memory are the classes used in the object, lazily loaded, which are not removed from memory. And you could be looking at a memory leak – njzk2 Dec 12 '14 at 14:02
  • possible duplicate of [Java not garbage collecting memory](http://stackoverflow.com/questions/10951812/java-not-garbage-collecting-memory) – Sarthak Mittal Dec 12 '14 at 14:02
  • Add some code here that demonstrates the issue. The particulars matter when it comes to garbage collection. – allTwentyQuestions Dec 12 '14 at 14:30

2 Answers2

0

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#gc%28%29

The keyword here is 'suggests'. Just because you call gc doesn't mean the Runtime has to listen at all. If you just nullify references when you are done using them, Java will do the cleanup work for you.

John
  • 3,769
  • 6
  • 30
  • 49
0

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.
G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40