What is garbage collection in java with example
Garbage collection in Java is a process by which the Java Virtual Machine (JVM) automatically reclaims memory occupied by objects that are no longer in use by the program. It helps manage memory efficiently by identifying and releasing memory occupied by objects that are no longer reachable or referenced by the program.
How Garbage Collection Works:
- Object Creation:
- When you create objects in Java using the
new
keyword, memory is allocated on the heap for those objects.
- When you create objects in Java using the
- Reference Tracking:
- The JVM keeps track of references to objects. If an object is referenced by at least one variable or is part of an active object graph, it is considered reachable.
- Mark and Sweep:
- During garbage collection, the JVM marks objects that are reachable, and then sweeps through the memory, deallocating memory occupied by objects that are not marked as reachable.
- Memory Reclamation:
- The memory occupied by unreachable objects is reclaimed, making it available for new object allocations.
Simple example:
/*
* Author: Zameer Ali Mohil
* */
public class GarbageCollectionExample {
public static void main(String[] args) {
// Creating objects
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
// Making obj1 null, removing reference
obj1 = null;
// Explicitly triggering garbage collection (Note: It's generally not needed)
System.gc();
// Creating more objects
MyClass obj3 = new MyClass();
MyClass obj4 = new MyClass();
// Making obj3 and obj4 null, removing references
obj3 = null;
obj4 = null;
// Explicitly triggering garbage collection (Note: It's generally not needed)
Runtime.getRuntime().gc();
}
}
class MyClass {
// Class members and methods
// This class is just used to create instances for the example
}
In this example:
- Objects
obj1
andobj2
are created. obj1
is set tonull
, removing the reference to the object.- The
System.gc()
andRuntime.getRuntime().gc()
statements are used to explicitly trigger garbage collection (though, in practice, it’s usually not necessary to manually trigger it). - Objects
obj3
andobj4
are created. obj3
andobj4
are set tonull
, removing references to the objects.
Keep in mind that while you can suggest garbage collection to the JVM using System.gc()
or Runtime.getRuntime().gc()
, the decision to perform garbage collection is ultimately up to the JVM, and it may choose not to perform garbage collection immediately.
In most cases, Java’s garbage collector works automatically, and developers don’t need to explicitly manage memory deallocation. The automatic garbage collection mechanism contributes to Java’s memory safety and ease of use.
What are the possible ways of making objects eligible for garbage collection (GC) in Java?
Objects in Java become eligible for garbage collection when there are no references to them. The Java Virtual Machine (JVM) has a garbage collector that automatically identifies and reclaims memory occupied by objects that are no longer reachable. Here are some common ways to make objects eligible for garbage collection:
1. Setting References to Null:
Explicitly setting a reference to null
means that the object it was pointing to is no longer accessible and becomes eligible for garbage collection.
/*
* Author: Zameer Ali Mohil
* */
MyClass obj = new MyClass();
// ...
obj = null; // obj is now eligible for garbage collection
2. Method Scope:
Objects created within a method have local scope. Once the method completes execution, local variables are no longer accessible, and the objects they reference become eligible for garbage collection.
/*
* Author: Zameer Ali Mohil
* */
void someMethod() {
MyClass localObj = new MyClass();
// ...
} // localObj is no longer accessible, and eligible for garbage collection
3. Reassigning Reference:
If a reference is reassigned to another object, the original object becomes unreachable and is eligible for garbage collection.
/*
* Author: Zameer Ali Mohil
* */
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
// ...
obj1 = obj2; // obj1 no longer references the original object and is eligible for garbage collection
4. Exiting Scope:
When a reference goes out of scope (e.g., local variables in methods or block scope), the associated objects become unreachable and are eligible for garbage collection.
/*
* Author: Zameer Ali Mohil
* */
{
MyClass obj = new MyClass();
} // obj is no longer accessible and eligible for garbage collection
5. Circular References:
Circular references, where objects reference each other in a cycle, can lead to memory leaks. If a group of objects is not reachable from the root of the object graph, they become eligible for garbage collection even if they reference each other.
/*
* Author: Zameer Ali Mohil
* */
class Node {
Node next;
}
Node node1 = new Node();
Node node2 = new Node();
node1.next = node2;
node2.next = node1; // Circular reference
// ...
// If node1 and node2 are no longer reachable, they are eligible for garbage collection
6. Weak References:
Using weak references allows objects to be eligible for garbage collection even if they have references. Weak references are typically used in scenarios where the object’s existence is tied to some other resource.
/*
* Author: Zameer Ali Mohil
* */
import java.lang.ref.WeakReference;
MyClass obj = new MyClass();
WeakReference<MyClass> weakRef = new WeakReference<>(obj);
obj = null; // obj is still weakly referenced, but eligible for garbage collection
It’s important to note that the decision to perform garbage collection is up to the JVM, and it may not occur immediately after an object becomes unreachable. The JVM’s garbage collector runs periodically and reclaims memory occupied by unreachable objects.