All 15 Garbage Collection questions
More in Garbage Collection
Advertisement
Back to results for “Diagnostics & Performance”
Java › Garbage Collection

What is garbage collection in the JVM, and what fundamental problem does it solve compared to manual memory management (like in C/C++)?

Beginner

Answer

Garbage collection automatically identifies and reclaims heap memory occupied by objects no longer reachable from any active reference (a local variable, static field, or another still-reachable object), freeing developers from manually tracking object lifetimes and explicitly deallocating memory -- this eliminates entire categories of memory bugs common in manually-managed languages, specifically use-after-free (accessing memory that's already been deallocated) and memory leaks caused by simply forgetting to free memory, though it introduces its own trade-offs like GC pause times and less predictable memory reclamation timing.
public void createObjects() {
    for (int i = 0; i < 1000; i++) {
        Object obj = new Object();  // allocated on the heap
    }  // once this loop iteration ends and 'obj' goes out of scope, the object becomes eligible for GC
    // No explicit free()/delete needed -- the garbage collector reclaims it automatically, eventually
}
Real-world example A Java web application processes millions of short-lived request objects per day without any manual memory deallocation code anywhere in the codebase, relying entirely on the JVM's garbage collector to automatically reclaim each request's associated objects once they're no longer referenced after the request completes.

Common follow-ups: What specifically makes an object 'eligible' for garbage collection -- reference counting, or something else?;What are the trade-offs of GC-managed memory versus manual memory management in terms of predictability and performance?