Skip to content

Chapter 25 of 37

Memory Management and Garbage Collection

Reason about heap, stacks, reachability, collectors, leaks, and resource cleanup.

40 minutes 10 quick checksBy Subha Prasad
Lesson 25 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Objects generally live on the heap; each invocation has a stack frame holding execution state and local values. The JVM may optimize placement while preserving observable behavior.

Reachability, not scope

List<byte[]> retained = new ArrayList<>();
// Retaining references keeps arrays reachable and prevents reclamation.
retained.add(new byte[1_000_000]);
retained.clear();

Collectors find objects unreachable from GC roots and reclaim them; timing is intentionally unspecified. Strong, soft, weak, and phantom references have different reachability roles. Java can still leak memory through caches, listeners, thread locals, and static collections. Heap sizing and collector choice are operational decisions driven by latency/throughput measurements. GC manages memory—not files, sockets, native handles, or business lifecycle—so close resources deterministically.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes heap?
Which Java term matches this description: Memory where objects and arrays are generally allocated.
Which statement best describes stack frame?
Which Java term matches this description: Per-invocation storage for local state and execution bookkeeping.
Which statement best describes garbage collection?
Which Java term matches this description: Automatic reclamation of objects no longer strongly reachable.
Which statement best describes strong reference?
Which Java term matches this description: A normal reference that keeps its reachable object alive.
Which statement best describes memory leak?
Which Java term matches this description: Unneeded objects retained through live references.

0 of 10 checks passed

Your progress is saved on this device.

Memory Management and Garbage Collection | Java Lesson | Subha Prasad