0

Does calling GC explicitly have an effect on system memory?

I am using a number of data structures like Arraylist and HashMap in my activity. There is a need of refilling updated data from web service each time a user loads the activity. It implies that when the user leaves the activity and come back again these data structures should come in the memory.

When a user leaves the activity and does not come to it again I don't want these data structure to occupy any memory.

So can that be performed by calling GC in onPause() of the activity? Is it a good practice to do so? What are the options if I want to do such things?

Félix Gagnon-Grenier
  • 7,344
  • 10
  • 45
  • 58
kaushal trivedi
  • 3,217
  • 1
  • 26
  • 44

2 Answers2

1

Firstly, System.gc() is just a request. There is no guarantee that the System will run the Garbage Collector.

Next, coming to your issue. If you are sure that the activity will be exited and be re-created for data updates, its better to assign all your Data structures in the current activity to NULL.

This you can do it in your onDestroy() method. This will ensure that all your DS objects are released and the System will consider for Garbage Collection when it runs the gc().

Hope this helps.

RainMaker
  • 41,717
  • 11
  • 78
  • 97
  • agreed with your answer but what i want is memory that is occupied in the activity should be reclaimed as soon as i leave it.At some other part of my application actually needs memory but as you said there is no garuntee that system will reclaim it as soon as i leave my activity.In short i want to call garbage collector to call for some activities only.Do you have idea regarding that? – kaushal trivedi Feb 07 '13 at 07:56
  • another thing is that if you allocate null reference to any thing it occupies memory as null is blank reference.It occupies 8 byte of memory if you are running 64 bit machine.so is it really good to allocate null to all objects. – kaushal trivedi Feb 07 '13 at 08:01
  • The System runs the Garbage Collector when it realizes that the memory is running **low**. Hence, most of the times, you need not worry about memory issues. All you need to concentrate on, is to release all your DS objects once you're done with them. – RainMaker Feb 07 '13 at 08:16
  • Also, setting all "no-longer-needed" objects to **NULL** is one of the better practices in programming. – RainMaker Feb 07 '13 at 08:17
0

You should first call clear all your data structure and set them to null. Calling GC may reduce device performance and its a request to garbage collector, It is not sure that GC will be executed.

so, rather then calling GC yourself just clear all DS and set them null.

DcodeChef
  • 1,382
  • 11
  • 16