17. Memory Management, GC, and Java Object Lifecycles | Java Backend Interview Prep - Study Chapter | QuizMaker

Prepare for JVM memory, garbage collection, object references, and memory leak questions.

Read
13m
Type
Chapter
Access
Free

Course

Java Backend Interview Prep

Topic

4. JVM & Interview Communication

Stack and Heap

Method calls and local variables live on stack frames. Objects live on the heap, and variables often hold references to those heap objects.

Garbage Collection

Java garbage collection finds objects that are no longer reachable from live references and reclaims their memory. You do not manually free memory like in C.

Memory Leaks in Java

Java can still leak memory if reachable references are kept unnecessarily. Common examples include static collections that keep growing, unclosed resources, caches without eviction, and listeners that are never removed.

Interview Framing

Say that GC handles unreachable objects, but developers still manage object lifecycles by avoiding accidental long-lived references and by closing external resources.

Interview Scenario Practice

Scenario 1: Static List Keeps Growing

Scenario: Memory usage keeps increasing because a static list stores every processed request.

Strong answer: This is a Java memory leak pattern. Objects remain reachable through the static list, so GC cannot reclaim them.

Why it works: Garbage collection only removes unreachable objects.

Common mistake: Saying Java cannot leak memory because it has GC.

Scenario 2: Unclosed File or DB Connection

Scenario: The app eventually runs out of file handles or database connections.

Strong answer: Use try-with-resources or framework-managed resource lifecycles. GC is not a substitute for deterministic external resource cleanup.

Why it works: Heap memory and external resources are related but not the same operational concern.

Common mistake: Waiting for finalizers or GC to close important resources.

Scenario 3: Object Eligible for GC

Scenario: An object was created inside a method and no reference escapes after the method returns.

Strong answer: The object can become eligible for GC after it is no longer reachable from live references.

Why it works: Java GC traces reachability, not whether the object is inside or outside a particular method textually.

Common mistake: Assuming objects are destroyed immediately at the closing brace.

Open on QuizMaker