Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Runtime.gc() in onLowMemory method

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

like image 384
JP Godara Avatar asked Oct 31 '25 03:10

JP Godara


2 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.

like image 67
fxrbfg Avatar answered Nov 01 '25 16:11

fxrbfg


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.

like image 30
user207421 Avatar answered Nov 01 '25 18:11

user207421