Topic 6. Memory and Garbage Collector

Memory behavior in Java is a core reliability topic. Many production failures are caused by reference lifetime mistakes, not syntax issues.

Stack and Heap

Basic memory model

stack and heap have different responsibilities:

  • stack stores method frames, local variables, and references,
  • heap stores objects and arrays,
  • method frame disappears after method completion,
  • heap object stays alive while reachable.
int age = 30;          // primitive value
String name = "Alex"; // reference to heap object

How Garbage Collector works

GC uses reachability analysis, not timer-based cleanup.

Simplified flow:

  1. JVM identifies GC Roots (active threads, stack references, static fields, etc.).
  2. Reachable objects are marked alive.
  3. Unreachable objects become reclaim candidates.
  4. Memory may be compacted to reduce fragmentation.

Garbage Collector

Key point: GC timing is nondeterministic. System.gc() is only a hint.

Generational memory model

Most JVM collectors rely on generations:

  • Young Generation: new objects,
  • Old Generation: long-lived objects,
  • Metaspace: class metadata.

Why it helps: many objects are short-lived, so frequent cheap young collections are effective.

GC pauses in practical terms

  • Minor GC: more frequent, typically shorter, mostly young generation.
  • Major/Full GC: less frequent, usually heavier, may involve old generation.

If service latency spikes, long or frequent GC pauses are common suspects.

Typical Java memory leak patterns

A Java memory leak usually means “objects remain reachable accidentally”, not “GC is broken.”

Common causes:

  1. unbounded static collections,
  2. cache without eviction policy,
  3. event listeners/subscriptions never removed,
  4. uncleared ThreadLocal in long-lived threads,
  5. heavyweight object graphs pinned by singleton components.

Example:

public class CacheHolder {
    private static final List<byte[]> CACHE = new ArrayList<>();

    public static void add(byte[] data) {
        CACHE.add(data); // unbounded growth
    }
}

Objects remain reachable through CACHE, so GC cannot reclaim them.

Writing GC-friendly code

  1. bound cache and queue sizes,
  2. release subscriptions/resources explicitly,
  3. avoid unnecessary long-lived references,
  4. reduce temporary allocations in hot loops,
  5. plan lifecycle for large buffers.

Practical diagnostics workflow

  1. Monitor heap usage and GC pause metrics.
  2. Capture heap dump when memory keeps rising.
  3. Use dominator tree to find who retains memory.
  4. Correlate memory growth with workload patterns.

Key takeaway

  • GC removes only unreachable objects.
  • Most memory issues are reference-graph design issues.
  • Memory management quality starts at architecture level.
Glossary
bytecode
Platform-independent compiled code that the JVM can execute.
class
A blueprint that defines fields and methods for objects in object-oriented programming.
object
A runtime instance of a class with its own state and behavior.
method
A named block of behavior that belongs to a class or object and can be called by code.
field
A variable stored inside a class or object that represents part of its state.
constructor
A special method-like block used to create and initialize a new object.
package
A namespace that groups related Java classes and helps organize code.
interface
A contract that defines methods a class can implement without prescribing all internal details.
generics
A language feature that lets code work with types as parameters while preserving type safety.
type erasure
The Java compiler process that removes most generic type details from runtime bytecode.
collection
A data structure that stores a group of elements and provides operations over them.
list
An ordered collection where elements have positions and duplicates are allowed.
set
A collection that stores unique elements and is commonly used for membership checks.
map
A key-value data structure where each key points to a value.
queue
A collection designed for processing elements in a defined order, often first-in-first-out.
lambda
A compact function-like expression used to pass behavior as data.
functional interface
An interface with one abstract method, suitable for lambdas and method references.
stream
A Java API for processing data sequences with operations such as map, filter, and reduce.
optional
A container object that represents a value that may or may not be present.
thread
An independent path of execution inside a running program.
synchronization
Coordination that protects shared data when multiple threads access it.
heap
The runtime memory area where Java objects are allocated.
stack
The runtime memory area that stores method calls, local variables, and call frames.
garbage collector
A JVM component that automatically frees memory occupied by objects no longer reachable.
memory leak
A situation where memory remains occupied because objects are still referenced but no longer useful.