
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ways to Call Garbage Collector (GC) in Java
This article explains the different ways of calling the garbage collector (GC) in Java. It also includes a brief introduction to garbage collection, various calling approaches, and relevant examples.
Garbage Collection (GC) in Java
In Java, the garbage collection is carried out by a daemon thread called the Garbage Collector (GC). Instead of waiting until the Java Virtual Machine (JVM) runs a garbage collector, we can request the JVM to run the garbage collector. There is no guarantee that the JVM will accept our request.
In Java, we can call the garbage collector (GC) manually in "two ways", which are:
Calling Garbage Collector using System Class
This is one of the common ways of calling the garbage collector using the System class. This class provides a static method gc(), which is used to call the garbage collector implicitly.
The System class is a final class (which can not be instantiated) that belongs to java.lang package. It provides access to system-related resources and functionalities.
Example
In the following example, we use the System class to call the garbage Collector gc by requesting from the JVM using the gc() method:
public class SystemClassTest { public static void main(String[] args){ SystemClassTest test = new SystemClassTest(); test = null; //using System class System.gc(); } public void finalize() { System.out.println("Garbage collected"); } }
Following is the output of the above program:
Garbage collected
Using Runtime Class
This is another way to call the garbage collection (GC) using the Runtime class. The "Runtime" is a singleton class in Java, and we can get a runtime object using the getRuntime() method. This class provides a gc() method, which is used to call the garbage collection.
Example
This is another example of calling the garbage collector (GC). In this example, we use the gc() method of the Runtime class to request the JVM to run the garbage collector:
public class RuntimeClassTest { public static void main(String[] args) { RuntimeClassTest test = new RuntimeClassTest(); test = null; Runtime.getRuntime().gc(); } public void finalize() { System.out.println("Garbage Collected"); } }
The above program produces the following output:
Garbage collected