Java – Call Runtime.gc() in the onLowMemory method

Call Runtime.gc() in the onLowMemory method… here is a solution to the problem.

Call Runtime.gc() in the onLowMemory method

Should we use Runtime.gc()? Or System.gc() for clearing memory in production code (manual garbage collection) and methods in the onLowMemory() Application class?

Solution

This is a bad practice, using System.gc() does not mean that you are manually using gc It just prompts the jvm to clean up the garbage. It is best not to use methods like finalize() in Object, neither of which provides any guarantees. In the javadoc of Application, it means that the system will execute gc after returning from this method, and do it the right way.

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() after onLowMemory() returns from this method, it will be another garbage collection job. Judging by the hint in javadoc, it is better to lose the link to the cache List<Object in the example> bigCache = null; After the method finishes, garbage collection occurs, collecting the cache list and freeing memory.

Related Problems and Solutions