Lesson 33: Garbage Collection Basics

03 Aug 2026 1 min Swarnil Singhai

Java automatically reclaims memory for objects no longer reachable from any live reference — no manual free() like C/C++.

Real-time example

A web server handling millions of requests never manually frees request objects — once a request finishes and nothing references it, GC reclaims it.

void handleRequest() {
    byte[] buffer = new byte[1024]; // allocated on heap
    process(buffer);
} // after this line, buffer is unreachable -> eligible for GC

What's happening

'Eligible for GC' doesn't mean 'immediately freed' — the JVM decides when to actually run collection, based on generational heuristics.

Memory leaks in Java usually mean something is unintentionally still holding a reference (e.g. a growing static list), not GC failing.

Advertisement