Calling Runtime.gc() in onLowMemory method

Viewed 331

Should we use Runtime.gc() or System.gc() for clearing memory (manual garbage collection) in production code in onLowMemory() method in Application class?

3 Answers

It's a bad practice, using System.gc() is not meaning you use manually gc it's only hint to jvm to wipe off garbage. Better to not use this method like finalize() in Object, both of them not provide any guarantee. In javadoc of Application said that system will perform gc after returning from this method and given way to do it in the right manner.

You should implement this method to release any caches or other unnecessary resources you may be holding on to. The system will perform a garbage collection for you after returning from this method.

Application javadoc

So when you use System.gc() in onLowMemory() method after return from this method, will be another garbage collection effort. From hint in javadoc it's better to lost link to caches in example List<Object> bigCache = null; after method end will be garbage collection that pick up that cache list and memory will free.

No. From the Javadoc:

You should implement this method to release any caches or other unnecessary resources you may be holding on to. The system will perform a garbage collection for you after returning from this method.

For clear the memory you can call both inside onLowMemory()

Both are same. System.gc() is effectively equivalent to Runtime.gc(). System.gc()internally calls Runtime.gc().

only difference is System.gc() is a class method where as Runtime.gc() is an instance method. So, System.gc() is more convenient.

Hope you get it.

Related