5

I am experiencing some out of memory issues on my app and want to call the garbage collector, but I am not sure in which method I should call it.

Here is my code:

 public static void CleanUpMemory(){
    System.runFinalization();
    Runtime.getRuntime().gc();
    System.gc();
 }

Currently I am calling this method in onStop() but is it better to call it inside onDestroy()?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
user5035668
  • 307
  • 1
  • 4
  • 16

3 Answers3

1

It is never a good practice to call the GC manually. Dalvik or ART simply knows better than us.

If your app requires a lot of memory to handle expensive operations, this is a good solution

<application
....
   android:largeHeap="true"> 
Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
0

It is better to leave the garbage collector to work alone.

When it needs to garbage collect memory it starts.

Consider that the call System.gc() is only a suggest to start the gc that operates when it really necessary.

From javadoc:

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. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Try to use your improvements to use less memory instead to call explicitly the gc (caching objects, using poolings and so on).

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • OK but my issues are out of memory errors and they are made when calling Async task -> doInBackground() method. – user5035668 Jul 22 '15 at 11:35
  • Most of the time OOM are not thrown in the place where the issue is. Use a profiler to see where it takes all the memory and fix it if you can – Marco Acierno Jul 22 '15 at 11:44
  • An OutOfMemory is not resolved with a call to the gc. You have to tune your app to use less memory. Calling gc is useful only to ask for a more frequent gc to reduce the time of each gc, but there are other techniques to use instead of calling it manually – Davide Lorenzo MARINO Jul 22 '15 at 12:03
0

It is not a good practice to call gc() directly in your activity(JVM knows when to run it).

If you are facing memory issues, try to find memory leaks in your app using MAT.

Also System.gc() call will not force a garbage collection.It is upto Dalvik to decide when to run gc

Renjith
  • 3,274
  • 19
  • 39