---
title: "JVM, memory, garbage collection, and JIT"
chapter: "13"
---

# JVM, memory, garbage collection, and JIT

The JVM loads classes, verifies bytecode, manages memory, schedules execution,
and optimizes hot code.

## Runtime memory

- Heap: objects and arrays, managed by garbage collection.
- Thread stack: frames, local variables, operand stacks, return information.
- Metaspace: class metadata in native memory.
- Code cache: compiled machine code.
- Native/direct memory: buffers, libraries, JVM structures.

`StackOverflowError` usually means excessive call depth. `OutOfMemoryError`
names different exhausted areas; heap is only one possibility.

## Class loading

Class loaders follow delegation rules and create type identity. The same class
name loaded by different class loaders is a different runtime type. Loading,
linking (verification, preparation, resolution), and initialization are
distinct phases.

## JIT compilation

The interpreter begins execution quickly. The JVM profiles running code and JIT
compiles hot methods to optimized machine code. Optimizations may inline,
eliminate allocations, specialize branches, and later deoptimize if assumptions
change. Warmup matters in benchmarks.

## Garbage collection

GC finds objects reachable from roots and reclaims the rest. Choose/tune a
collector from pause, throughput, footprint, and heap needs. Defaults are often
good. Reduce allocation or retain less only after measurement.

## Diagnose

Use Java Flight Recorder, Java Mission Control, `jcmd`, thread dumps, heap
dumps, GC logs, native memory tracking, and OS metrics. A heap dump can contain
secrets and personal data; protect it.

## Feynman check

The heap is a warehouse, stacks are each worker's desk, GC removes packages no
reachable inventory record points to, and the JIT replaces frequently followed
instructions with a faster local route.
