What is System.gc() and Runtime.gc()?

A typical Garbage Collection (GC) algorithm in Java identifies garbage by traversing all non-garbage objects in the heap, and inferring that any object not visited must be garbage. Calling one of the gc() methods does not force garbage collection to happen, either; it only suggests to the JVM that now might be a good time for some garbage collection.

system.gc()

System.gc() is used to invoke the garbage collector and on invocation garbage collector will run to reclaim the unused memory space. It will attempt to free the memory that are occupied by the discarded objects. The System.gc() is a static method so it's a little bit more convenient to use. Calling it can add unnecessary performance issues to your application, and it is not guaranteed to actually perform a collection. It is actually possible to disable explicit System.gc() via the java argument -XX:+DisableExplicitGC. The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc().

runtime.gc()

Java Runtime class is used to interact with java runtime environment. The java.lang.Runtime.gc() method runs the garbage collector. Calling this method suggests that the JVM (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 virtual machine has made its best effort to recycle all discarded objects.

system.gc() VS runtime.gc()

Both are same. There is no difference between System.gc() and Runtime.gc() . System.gc()internally calls Runtime.gc(). The only difference is System.gc() is a class method whereas Runtime.gc() is an instance method. So, System.gc() is more convenient. Also, Runtime.gc() is a native method whereas System.gc() is non - native method which in turn calls the Runtime.gc()