The Java Garbage Collector (GC) is a mechanism provided by the Java Virtual Machine (JVM) to automate the management of memory.
When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Garbage Collector is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
In a programming language like C, allocating and deallocating memory is a manual process. In Java, process of deallocating memory is handled automatically by the garbage collector.
Examples when objects become eligible for garbage collection
Nullifying a reference: When an object reference is set to null
, the object it was pointing to becomes eligible for garbage collection if there are no other references to it.
public class GCDemo {
public static void main(String[] args) {
MyClass obj = new MyClass(); // obj is a strong reference to MyClass instance
obj = null; // Now, the MyClass instance is eligible for GC
}
}
class MyClass {
// Some fields and methods
}
Reassigning a reference: When an object reference is reassigned to another object, the original object may become eligible for garbage collection if there are no other references to it.
public class GCDemo {
public static void main(String[] args) {
MyClass obj1 = new MyClass(); // obj1 references MyClass instance #1
MyClass obj2 = new MyClass(); // obj2 references MyClass instance #2
obj1 = obj2; // MyClass instance #1 is now eligible for GC
}
}
class MyClass {
// Some fields and methods
}
Objects created inside a method: Objects created inside a method are eligible for garbage collection once the method execution is complete, and the stack frame for the method is removed, assuming there are no external references.
public class GCDemo {
public static void main(String[] args) {
method();
}
public static void method() {
MyClass obj = new MyClass(); // obj is a local reference
// MyClass instance is eligible for GC after method() completes
}
}
class MyClass {
// Some fields and methods
}