Java Garbage Collection: Automated Memory Management for Efficient Programming
Learn about Java Garbage Collection, the automatic process that reclaims memory occupied by unreferenced objects. This essential feature enhances memory management by efficiently destroying unused objects, offering a significant advantage over manual memory management techniques like C's free()
and C++'s delete()
. Explore how garbage collection works and its impact on Java application performance.
Java Garbage Collection
In Java, garbage means unreferenced objects.
Garbage Collection is the process of reclaiming runtime unused memory automatically. It is a way to destroy unused objects, providing better memory management compared to C's free()
and C++'s delete()
functions.
Advantages of Garbage Collection
- It makes Java memory efficient by removing unreferenced objects from heap memory.
- It is automatically done by the garbage collector (a part of JVM), so no extra effort is needed.
How Can an Object be Unreferenced?
There are several ways an object can become unreferenced:
- By nulling the reference:
Employee e = new Employee();
e = null;
Employee e1 = new Employee();
Employee e2 = new Employee();
e1 = e2; // now the first object referred by e1 is available for garbage collection
new Employee();
finalize()
Method
The finalize()
method is invoked each time before an object is garbage collected. This method can be used to perform cleanup processing. It is defined in the Object class as:
protected void finalize(){}
Note: The Garbage Collector of JVM collects only those objects that are created by the new
keyword. If you have created any object without new
, you can use the finalize
method to perform cleanup processing.
gc()
Method
The gc()
method is used to invoke the garbage collector to perform cleanup processing. The gc()
method is found in the System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector (GC). This thread calls the finalize()
method before an object is garbage collected.
Example of Garbage Collection in Java
FileName: TestGarbage1.java
public class TestGarbage1 {
public void finalize() {
System.out.println("object is garbage collected");
}
public static void main(String[] args) {
TestGarbage1 s1 = new TestGarbage1();
TestGarbage1 s2 = new TestGarbage1();
s1 = null;
s2 = null;
System.gc();
}
}
Output
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.