What is System.gc() and Runtime.gc()?
A typical Garbage Collection (GC) algorithm detects garbage objects by traversing the heap and considering any objects not visited as potential garbage. It's important to note that invoking one of the gc() methods does not mandate immediate garbage collection; rather, it serves as a suggestion to the JVM, indicating that it may be an opportune moment to initiate garbage collection.
The invocation of System.gc() in Java is utilized to trigger the garbage collector, prompting it to reclaim unused memory space by freeing up the memory occupied by discarded objects. Although System.gc() is a static method and offers convenience, it is important to note that calling it can potentially introduce unnecessary performance overhead to your application. Furthermore, there is no guarantee that the garbage collection will actually take place as the Java Language Specification does not mandate the JVM to initiate a garbage collection upon calling System.gc(). It is also worth mentioning that explicit System.gc() can be disabled using the -XX:+DisableExplicitGC Java argument.
The Java Runtime class provides a means to interact with the Java runtime environment. The gc() method in java.lang.Runtime is used to invoke the garbage collector. By calling this method, it signifies the suggestion to the JVM (Java Virtual Machine) to prioritize the recycling of unused objects, thereby freeing up the memory they currently occupy for efficient reuse. After the method call, the virtual machine diligently attempts to recycle all discarded objects, ensuring optimal memory utilization.
system.gc() VS runtime.gc()
Both System.gc() and Runtime.gc() serve the same purpose of invoking the garbage collector in Java. System.gc() internally calls Runtime.gc(). The only distinction is that System.gc() is a class method, while Runtime.gc() is an instance method. Therefore, System.gc() is often considered more convenient to use. Additionally, it's worth noting that Runtime.gc() is a native method, whereas System.gc() is a non-native method that ultimately delegates the task to Runtime.gc().