java’s garbage collector automatically reclaims memory by deallocating objects that are no longer reachable.
this is managed by jvm
garbage collection primarily works on the heap.
heap memory - java objects are stored in the heap, a region of memory divided into areas like:
young generation - new objects are allocated here.
old generation - for long lived objects
meta-space - for class metadata.
reachability - an object is reachable if it is accessible by the chain of references from root. if it is not it is elidgible for garbage collection.
marking - the gc traverse the object graphing, marking all objects that are being referenced . unmarked objects are considered for garbage collection
sweeping - the gc reclaims the memory by freeing the objects or moving the objects.
compaction - some gc compact the heap by moving live objects together reducing fragmentation and improving memory allocation frequency.
prevents memory leaks by automatically freeing unused memory
eleminates manual memory management like in c/c++.
reduces bugs like dangling pointer and double -free errors.
unpredictable timing
performance overhead
limited control
class Main {
public static void main(String[] args) {
Box b1 = new Box(); // b1 references a Box object
Box b2 = new Box(); // b2 references another Box object
b1 = null; // b1's object is now eligible for GC
b2 = b1; // b2's original object is also eligible for GC
System.gc(); // Suggest GC
}
}