The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·41

Memory and Performance

Where Java's memory goes and how to make code fast without guessing. Covers stack versus heap, object headers and references, allocation and TLABs, escape analysis and scalar replacement, CPU cache effects and data layout, boxing, string interning and deduplication, then measurement with JMH and profiling with JFR, async-profiler, jcmd, jstack, jmap, VisualVM and JMC. Compared with how Go, Rust, C, C++, Zig, C# and Python lay out memory and with their profilers and benchmark harnesses.

31 topics · ~29 min read · 30-question quiz
Updated Suggest a correction

Start here: where the memory goes, and how to measure

The first rule: measure, don't guess

Performance work goes wrong in a predictable way: someone guesses what's slow, rewrites it cleverly, and the system is no faster because the time was going somewhere else. The method is always the same: define the goal (p99 latency under 200 ms at 500 requests per second; a batch finishing in an hour), measure where time and memory actually go, change one thing, and measure again. In a typical backend, most time goes to waiting on the database and other services (Volume 4 and chapter 52), so check those first; this chapter is about what happens inside the JVM once they're fine.

What things cost in memory

Java hides memory, so its costs surprise people. The program below stores a million values in different ways and measures heap growth after garbage collection:

Java
int[] prices = new int[n];                          // primitives in one block
List<Integer> boxed = new ArrayList<>();            // a reference to a separate Integer object each
Map<Integer, Integer> map = new HashMap<>();        // a node object, key object and value object each
List<Item> items = new ArrayList<>();               // record Item(String name, int pricePaise)
Text
1M prices as int[]:                        4.2 bytes each
1M prices as List<Integer>:               21.7 bytes each
1M entries in HashMap<Integer,Integer>:   73.5 bytes each
1M Item(name, price) records:             85.3 bytes each

An int is 4 bytes. As an Integer object it's 16 (a 12-byte object header plus the value, rounded up to a multiple of 8) plus a 4-byte reference in the list. A HashMap entry needs a 32-byte node, two boxed integers and a slot in the table: 18× the raw data. An Item with a short name is a 24-byte record, a 24-byte String and the string's byte array. None of this matters for a thousand objects; for a cache of ten million it decides whether the service fits in its container.

Asking the heap what's in it

You don't have to calculate: the JVM will tell you. jcmd <pid> GC.class_histogram (or the same command called in-process, as here) lists every class by instance count and bytes:

Text
 num     #instances         #bytes  class name
   1:       3000285       48004560  java.lang.Integer
   2:       1020742       33336600  [B                      ← byte arrays (string contents)
   3:       1006481       32207392  java.util.HashMap$Node
   4:       1020570       24493680  java.lang.String
   5:       1000000       24000000  Basics$Item

Three million Integer objects (48 MB) is the boxing from the list and the map. In a real service you'd take this histogram, or a full heap dump (jcmd <pid> GC.heap_dump, opened in Eclipse MAT or VisualVM), when memory grows, and see at a glance which structure is responsible.

Where the time goes: three effects

  • Allocation is cheap, but not free. Creating an object is a pointer bump in a thread-local buffer, and short-lived objects cost the GC almost nothing. The JIT can even remove allocations entirely (escape analysis) when an object never leaves a method: the lab's 50 million temporary records caused 0 garbage collections with it on and 60 with it off.
  • Memory layout matters more than instruction count. The CPU reads memory in 64-byte cache lines and prefetches sequential access. Reading a 2D array row by row was 17× faster than column by column in the lab, with identical arithmetic. Arrays of primitives beat arrays of objects scattered across the heap.
  • The JIT changes what you measure. A naive timing loop measures the interpreter, the compiler, or nothing at all: the lab's loop whose result was never used ran in 0.0 ms because the JIT deleted it. Use JMH (the Java Microbenchmark Harness) for micro-benchmarks, and profilers for real applications.

Profilers

A profiler shows where a running program spends its time. Java Flight Recorder (JFR) is built into the JDK and cheap enough for production (-XX:StartFlightRecording or jcmd <pid> JFR.start); open recordings in JDK Mission Control. async-profiler produces flame graphs: each bar is a method, its width the share of samples in which it was on the stack, so the widest towers are where time goes. Profile under realistic load, because a profile of an idle service shows only the profiler.

How deep to go in memory and performance

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 State the measure-first method; know objects cost headers and references
L2 Estimate memory of common structures; use histograms, JFR and JMH
L3 Explain object layout, TLABs, escape analysis, cache effects, false sharing and benchmark pitfalls
L4 Diagnose memory leaks, allocation hot spots and CPU hot spots from heap dumps, flame graphs and GC logs
L5 Set performance budgets and capacity plans; optimise data layout for a hot path
L6 Build a performance culture: continuous benchmarking, regression gates, production profiling

Method first

The performance workflow

Performance work fails most often from optimising the wrong thing. The discipline is the same in every language:

  1. Define the goal in user terms: p99 latency under 200 ms at 2,000 requests per second, or a batch finishing in under 10 minutes, or the heap fitting in a 2 GB container.
  2. Measure the real system under realistic load. Find where time and memory actually go with profiles, not intuition.
  3. Form a hypothesis about the bottleneck (CPU, allocation and GC, lock contention, I/O wait, a downstream dependency, an algorithm).
  4. Change one thing, and measure again with the same method.
  5. Stop when the goal is met.

The USE method (Utilisation, Saturation, Errors per resource) and the RED method (Rate, Errors, Duration per service) from Vol. 6 tell you which resource is the bottleneck. Profilers tell you which code is responsible.

In backend services, the biggest wins are usually not micro-optimisations. They're N+1 queries, missing indexes, chatty remote calls, unbounded result sets, lock contention, missing caches, and excessive allocation from serialisation. Profile before you rewrite loops.

Where data lives

Stack versus heap

Stack Heap
Allocation Bump the stack pointer when a function is entered (essentially free) Find space (JVM: a TLAB pointer bump; C: malloc free lists)
Deallocation Automatic at function return GC (Java, Go, C#), free (C), drop (Rust, C++ destructors), or allocator/arena reset (Zig)
Lifetime Bounded by the function call Arbitrary
Size Small (Java platform threads ~512 KB–1 MB, Go goroutines start at a few KB and grow, OS main threads ~8 MB) Large
Locality Excellent (hot in cache) Depends on allocation pattern and GC compaction
Sharing between threads No (each thread has its own) Yes

What goes where, per language:

Interactive diagram: Where the bytes go: an int, an Integer, a HashMap entry. It needs JavaScript; the text around it says the same.
  • Java: local primitives and references live in stack frames, and every object lives on the heap, conceptually. In practice the JIT's escape analysis can avoid heap allocation for objects that never escape (below). You don't control this directly.
  • C#: struct locals live on the stack (or inline in their containing object). class instances are on the heap. stackalloc and Span<T> give explicit stack buffers.
  • Go: the compiler decides by escape analysis. A value whose address escapes the function (returned, stored in the heap, captured by a goroutine, put in an interface) goes to the heap; otherwise it stays on the stack. go build -gcflags=-m prints each decision.
  • Rust, C, C++, Zig: you decide. Locals are on the stack. Heap allocation is explicit: Box::new/Vec (Rust), malloc (C), new/make_unique (C++), allocator.create (Zig). Rust's Vec<T> stores its elements contiguously on the heap with a (ptr, len, cap) header on the stack.
  • Python: everything is a heap object, including integers (small ints from −5 to 256 are cached singletons).
Go
// Go: see the compiler's escape decisions
func newPoint() *Point { p := Point{1, 2}; return &p }    // "moved to heap: p" (the address escapes)
func sum(xs []int) int { t := 0; for _, x := range xs { t += x }; return t }   // t stays on the stack
// $ go build -gcflags='-m' ./...

Object layout and references

A HotSpot object (chapter 40) has a header (12 bytes classically: an 8-byte mark word plus a 4-byte compressed class pointer; 8 bytes with compact object headers, the default from JDK 27), then fields, padded to 8 bytes. Fields are reordered by size to reduce padding. References are 4 bytes with compressed oops (heaps under about 32 GB) or 8 bytes otherwise.

Measure, don't guess, with JOL (Java Object Layout):

Java
// org.openjdk.jol:jol-core
System.out.println(ClassLayout.parseClass(Order.class).toPrintable());
System.out.println(GraphLayout.parseInstance(orderList).toFootprint());   // whole object graph
Text
com.shop.Order object internals:   (12-byte header layout)
OFF  SZ               TYPE DESCRIPTION
  0   8                    (object header: mark)
  8   4                    (object header: class)
 12   4                int Order.items
 16   8               long Order.id
 24   4   java.lang.String Order.customer
 28   4 java.math.BigDecimal Order.total
Instance size: 32 bytes

What things really cost (12-byte headers, compressed oops):

Value Size
int field 4 bytes
Integer object 16 bytes (header 12 + value 4), plus a 4-byte reference to it
Long / Double object 24 bytes (12 + 8, padded to 24)
Empty String ~40 bytes (a String object of 24 bytes + an empty byte[] of 16)
"hello" (Latin-1 compact string) 24 (String) + 24 (byte[] with a 16-byte array header + 5 bytes, padded) = 48 bytes
ArrayList<Integer> with 1M elements ~4 MB of references + 16 MB of Integers + slack ≈ 20+ MB, versus 4 MB for an int[]
HashMap entry ~32–48 bytes per Node + table slot + key and value objects

That's the object overhead tax Java pays for uniform reference semantics. Valhalla value classes and flattened arrays aim to remove much of it. Today, use primitive arrays and primitive collections for large numeric datasets (fastutil, Eclipse Collections, HPPC), and avoid wrapper types in hot data structures.

Compare a Rust Vec<(u64, u32)> with 1M elements: 16 MB, contiguous, no headers, no pointers. C# List<(long, int)>: about 16 MB, contiguous, because value tuples are structs. Go []struct{ID uint64; N uint32}: the same. Layout control is the main memory advantage of value-type languages.

Allocation and TLABs

The JVM makes allocation cheap: each thread allocates into its own TLAB in eden with a pointer bump, with no locking (chapter 40). Allocating a small object costs about 10–20 ns including initialisation, but every allocated byte must eventually be dealt with by the GC. Allocation rate (MB/s) is therefore the primary GC driver:

  • A service allocating 1 GB/s with a 1 GB young generation runs a young GC about every second.
  • Halving the allocation rate roughly halves young-GC frequency and CPU spent in GC.

Common high-allocation culprits in backend code: JSON (de)serialisation into intermediate trees (JsonNode), string concatenation and formatting in logging (log.debug("x=" + x) builds the string even when debug is off; use log.debug("x={}", x)), boxing in collections and streams, defensive copies, regex Pattern.compile in loops (compile once into a static final), exceptions with stack traces used for control flow, String.format in hot paths, and large intermediate byte[] buffers instead of streaming.

Escape analysis and scalar replacement

C2 performs escape analysis: does an object allocated in a method ever escape, by being stored in a field or static, returned, passed to a method that isn't inlined, or published to another thread? If it doesn't escape (after inlining), C2 can apply:

  • Scalar replacement: don't allocate the object at all. Its fields become local variables (registers).
  • Lock elision: synchronized on an object that no other thread can see is removed.
Java
record Point(double x, double y) {
    Point plus(Point o) { return new Point(x + o.x, y + o.y); }
    double len() { return Math.hypot(x, y); }
}

double pathLength(double[] xs, double[] ys) {
    double total = 0;
    for (int i = 1; i < xs.length; i++) {
        var a = new Point(xs[i - 1], ys[i - 1]);     // after inlining, neither Point escapes:
        var d = new Point(xs[i] - a.x(), ys[i] - a.y());
        total += d.len();                            // C2 scalar-replaces them: zero allocations in the loop
    }
    return total;
}

The limits are what surprise people:

  • It depends on inlining. If a method that receives the object isn't inlined (too big, megamorphic, or the inlining budget is exhausted), the object escapes.
  • Control-flow merges can defeat it in C2: an object assigned in two branches and merged into one variable. Graal's partial escape analysis handles more of these cases.
  • Objects that escape only on a rare path may still be allocated (Graal's partial escape analysis allocates them lazily on that path; C2 mostly can't).
  • Large arrays and arrays of unknown length usually aren't scalar-replaced.
  • It's invisible in the source. Verify with allocation profiling (JFR, async-profiler -e alloc) or JMH's -prof gc (gc.alloc.rate.norm, bytes allocated per operation).

Go's compile-time escape analysis is simpler but deterministic and inspectable (-gcflags=-m). Rust and C++ don't need it, since you choose stack or heap explicitly, though LLVM can sometimes remove heap allocations too (heap-to-stack promotion of Box happens in limited cases).

Boxing and unboxing

Autoboxing silently converts int ↔ Integer. The costs are allocation (outside the Integer cache range of −128..127), pointer chasing, and NullPointerException on unboxing:

Java
Map<String, Integer> counts = new HashMap<>();
int c = counts.get("missing");          // NPE: unboxing null

Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) sum += i;   // allocates up to ~1M Long objects (sum = Long.valueOf(sum + i))
long fast = 0;                                    // primitive: no allocation

// Streams: use primitive specialisations
int total = orders.stream().mapToInt(Order::items).sum();      // IntStream, no boxing
Integer total2 = orders.stream().map(Order::items).reduce(0, Integer::sum);   // boxes every element

Escape analysis removes some boxing, but don't count on it in hot paths. C# generics and Rust, Go and C++ templates don't box at all. Kotlin hides the distinction: Int compiles to int where possible and boxes when nullable (Int?) or used as a generic argument.

Strings: interning, deduplication and allocation

  • String literals are interned: identical literals share one String object in the JVM's string table, so "abc" == "abc" is true for literals. That's an implementation detail; always compare strings with equals.
  • String.intern() adds a string to that table and returns the canonical instance. It can save memory for huge numbers of repeated strings (country codes, status values parsed from input), but the string table is a fixed-size native hash table (-XX:StringTableSize), and interning has CPU cost. Prefer a local deduplication map you control, or enums.
  • G1 string deduplication (-XX:+UseStringDeduplication, also supported by other collectors since JDK 18): the GC finds String objects with equal contents and makes them share one backing byte[]. That's cheap and automatic, and worth trying for services holding many duplicate strings (parsed JSON, cached rows).
  • Compact strings (JDK 9) store Latin-1 text as one byte per char, roughly halving memory for ASCII-heavy data.
  • substring has copied since JDK 7u6. Earlier versions shared the parent array and could leak huge strings through tiny substrings.
  • Building strings: StringBuilder for loops. Single-expression concatenation compiles to invokedynamic StringConcatFactory, which is efficient.

Other languages: Go strings share backing bytes, so substrings are slices of the original. That's cheap, but a small substring keeps a large source string alive (strings.Clone copies). Rust gives you &str slices (borrowed, zero-copy) versus String (owned), with Cow<str> for "borrow when possible, copy when needed". Python interns identifier-like strings automatically and offers sys.intern. C# has string.Intern and ReadOnlySpan<char> slicing without allocation.

Hardware effects

CPU caches and data layout

Vol. 1 ch. 7 covers the hardware: L1 is about 1 ns, L2 about 4 ns, L3 about 10–40 ns, and DRAM about 80–100 ns. A cache miss to DRAM costs as much as hundreds of simple instructions. Memory layout often matters more than instruction count:

  • Contiguous, sequential access (arrays) lets the hardware prefetcher stream data in. Every 64-byte line fetched is fully used.
  • Pointer chasing (linked lists, trees of small objects, List<Integer>) means each step is a dependent load, potentially a cache miss, and the prefetcher can't help.
Java: Order[] (array of references) ref ref ref ref ref ref Order Order Order scatteredmisses AoS: struct Order { id; total; status } [] (C, Rust, Go, C#) [id total st][id total st][id total st] loads unused fields SoA: totals[] ids[] statuses[] [total total total total total total] only needed bytes columnar DBs, ECS engines and Arrow use SoA
Array of structs versus struct of arrays, and Java's array of references. Summing one field touches every cache line in AoS, only the needed lines in SoA, and scattered lines through pointers in Java object arrays.
Java
// The classic demonstration: same work, very different speed
int[][] grid = new int[4096][4096];
long rowMajor = 0, colMajor = 0;
for (int i = 0; i < 4096; i++) for (int j = 0; j < 4096; j++) rowMajor += grid[i][j];  // sequential: fast
for (int j = 0; j < 4096; j++) for (int i = 0; i < 4096; i++) colMajor += grid[i][j];  // strided: several times slower

Practical rules for Java backends:

  • Prefer ArrayList and arrays to LinkedList, and open-addressing primitive maps for huge numeric maps.
  • For analytics-style hot loops over many records, consider columnar layouts: parallel primitive arrays (long[] ids; double[] totals;) instead of List<Order>.
  • Keep hot objects small. Separate rarely used fields (cold data) into another object.
  • False sharing (chapter 38) is the multi-core version of this effect.
  • The Vector API (incubator) gives explicit SIMD. C2 also auto-vectorises simple loops over primitive arrays.

Rust, C, C++ and Zig give full layout control: #[repr(C)], #[repr(align(64))], alignas, packed structs, explicit SoA, arena-allocated nodes, and Zig's std.MultiArrayList (automatic SoA for a struct type). That control is why game engines, databases and HFT systems use these languages.

Zig
// Zig: a struct-of-arrays container, generated from a struct type at compile time
const Order = struct { id: u64, total: f64, status: Status };
var orders = std.MultiArrayList(Order){};
// orders.items(.total) is a contiguous []f64: perfect for summing or SIMD

Measuring

Benchmarking with JMH

Naive Java benchmarks (System.nanoTime() around a loop in main) are almost always wrong, for several reasons:

  • They measure interpreted or partially compiled code (no warmup).
  • Dead-code elimination: the JIT removes computation whose result is unused.
  • Constant folding: inputs known at compile time are computed once.
  • OSR compiles the loop differently from how real code would run.
  • GC pauses land randomly in one measurement.
  • Timer resolution and loop overhead distort tiny operations.

JMH (Java Microbenchmark Harness, by the HotSpot engineers) handles these properly:

Java
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(value = 2, jvmArgs = {"-Xms2g", "-Xmx2g"})       // fresh JVMs: profile pollution between benchmarks is avoided
@State(Scope.Thread)
public class ParseBench {
    @Param({"10", "1000"}) int size;
    String json;

    @Setup public void setup() { json = Fixtures.ordersJson(size); }

    @Benchmark public List<Order> jackson() throws Exception { return mapper.readValue(json, ORDERS_TYPE); }  // return the result: no DCE

    @Benchmark public void loop(Blackhole bh) {            // or consume values through a Blackhole
        for (var o : orders) bh.consume(o.total());
    }
}
// $ java -jar target/benchmarks.jar ParseBench -prof gc     # adds gc.alloc.rate.norm (bytes per op)
// $ … -prof async:output=flamegraph                         # integrate async-profiler

Equivalents: Rust criterion (statistical analysis, regression detection) and the built-in #[bench] on nightly; Go's testing.B (go test -bench . -benchmem reports allocations per op) with benchstat to compare runs; C++ Google Benchmark and nanobench; .NET BenchmarkDotNet (excellent, JMH-like); Python timeit and pyperf; Zig's std.time.Timer (and community harnesses such as zBench).

Microbenchmarks answer narrow questions ("is A faster than B in isolation?"). For services, use load tests (Gatling, k6, JMeter, wrk2, Vol. 11) against realistic deployments, and profile production.

Profiling: what to measure

Question Tool type
Where is CPU time spent? CPU sampling profiler → flame graph
Where is wall-clock time spent, including waiting? Wall-clock profiler (samples all threads, including blocked ones)
Who allocates the most? Allocation profiler
What is holding memory? Heap dump analysis (dominator tree, retained size)
Why are threads stuck? Thread dumps, lock profiling
What happened during that latency spike? Continuous recording (JFR), tracing (Vol. 6)

Flame graphs (Brendan Gregg): the x-axis is the share of samples (not time order), the y-axis is stack depth, and wide plateaus at the top are where time is spent. Read them by looking for wide boxes, then walking down to find the caller you control.

Java Flight Recorder and Mission Control

JFR is a low-overhead (about 1% by default) event recorder built into the JVM, safe to run continuously in production. It records CPU samples, allocation samples, GC events, lock contention, thread park, I/O, exceptions, class loading, safepoints, virtual-thread pinning, JIT compilation, and custom application events:

Terminal
# Start with the JVM
$ java -XX:StartFlightRecording=duration=0,maxage=6h,maxsize=500m,filename=/recordings/app.jfr,settings=profile -jar app.jar
# Or attach at run time
$ jcmd <pid> JFR.start name=incident settings=profile duration=2m filename=/tmp/incident.jfr
$ jcmd <pid> JFR.dump name=incident filename=/tmp/now.jfr
$ jfr print --events jdk.GarbageCollection /tmp/now.jfr | head
$ jfr summary /tmp/now.jfr
Java
// Custom events: cheap when disabled, recorded with stack traces when enabled
@Name("shop.Checkout") @Label("Checkout")
class CheckoutEvent extends jdk.jfr.Event {
    @Label("Order Id") String orderId;
    @Label("Items") int items;
}
var e = new CheckoutEvent();
e.begin();
… checkout …
e.orderId = id; e.items = n;
e.commit();                      // duration measured automatically

JDK Mission Control (JMC) opens .jfr files and provides automated analysis ("Automated Analysis Results" flags issues like high GC pressure or lock contention), flame views, memory and thread views. JFR event streaming (JDK 14) lets agents consume events in-process for continuous monitoring. Spring Boot and Micrometer can surface JFR data, and many APMs ingest it.

async-profiler

async-profiler is an open-source low-overhead sampling profiler for HotSpot. It combines Linux perf_events (or itimer) with HotSpot's AsyncGetCallTrace, so it has no safepoint bias. Many traditional Java profilers sample only at safepoints, which skews results toward safepoint polls. It also sees native frames (JIT compiler threads, GC, libc, kernel). Modes:

Terminal
$ asprof -d 30 -e cpu -f /tmp/cpu.html <pid>          # CPU flame graph
$ asprof -d 30 -e wall -t -f /tmp/wall.html <pid>     # wall-clock, per thread: finds blocking/waiting
$ asprof -d 30 -e alloc -f /tmp/alloc.html <pid>      # allocation flame graph (TLAB-based sampling)
$ asprof -d 30 -e lock -f /tmp/lock.html <pid>        # lock contention
$ asprof -e cpu,alloc,lock -d 60 -o jfr -f /tmp/all.jfr <pid>   # JFR output, viewable in JMC or IntelliJ

It's also built into IntelliJ IDEA's profiler, and runs as a Java agent for continuous profiling (Pyroscope, Grafana's continuous profiling).

jcmd, jstack, jmap, jconsole and VisualVM

Tool Purpose Typical use
jcmd (the Swiss army knife) Sends diagnostic commands to a running JVM jcmd (list JVMs), jcmd <pid> help, VM.flags, VM.system_properties, GC.heap_info, GC.class_histogram, GC.heap_dump /tmp/h.hprof, Thread.print, Thread.dump_to_file -format=json (includes virtual threads), VM.native_memory summary, JFR.start/dump, Compiler.codecache
jstack Thread dumps Run it 3 times, 5 seconds apart, and compare: threads stuck in the same frame are blocked; BLOCKED (on object monitor) shows contention; deadlocks are reported
jmap Heap histograms and dumps (jmap -histo:live, -dump:live,format=b,file=…) Largely superseded by jcmd GC.*
jstat GC statistics over time (jstat -gcutil <pid> 1s) Quick GC health checks
jconsole Basic JMX GUI: heap, threads, MBeans Local quick looks
VisualVM GUI: monitoring, sampler (CPU and memory), heap dump browser, thread views Development and staging
JMC JFR analysis Production incident analysis
Eclipse MAT Heap dump analysis: dominator tree, leak suspects report, OQL Finding memory leaks

In containers, the tools must run in the same container or namespace as the JVM (kubectl exec … jcmd 1 …). Distroless or JRE-only images may lack them, so plan for it with a debug sidecar, ephemeral containers, or JFR configured to dump to a volume.

Finding a memory leak

A Java memory leak means objects stay reachable that you no longer need. Typical causes:

  • Unbounded caches and static maps (a static Map that's only ever added to). Use bounded caches (Caffeine, chapter 53).
  • Listeners and callbacks registered and never removed.
  • ThreadLocals in pooled threads (values live as long as the thread does).
  • Class loader leaks on redeploy (chapter 40).
  • Unclosed resources holding buffers.
  • Huge in-flight queues (an executor's unbounded queue during overload).
  • Hibernate first-level caches in long sessions or batch jobs (chapter 49).

The workflow:

  1. Confirm from GC logs or metrics that heap after GC (the live set) grows over time and doesn't plateau.
  2. Capture two heap dumps some time apart, or one at OOM (-XX:+HeapDumpOnOutOfMemoryError). Dumping pauses the JVM and writes a file roughly the size of the heap, so be careful in production.
  3. Analyse in Eclipse MAT. The dominator tree sorts by retained size (the memory that would be freed if an object were collected). Follow "path to GC roots" (excluding weak references) to see who is holding the leak, such as ConcurrentHashMap inside a static field of MetricsRegistry.
  4. Compare class histograms (jcmd GC.class_histogram) over time for a cheaper, live view of which classes grow.

Native memory leaks (RSS grows while the heap is flat): use NMT (-XX:NativeMemoryTracking=summary, then jcmd VM.native_memory summary.diff against a baseline) and look for growth in thread count (stacks), direct buffers, metaspace, or glibc arena fragmentation (MALLOC_ARENA_MAX=2 is a common mitigation). jemalloc's profiling or async-profiler's native-memory mode can find leaks in native libraries.

Profilers and memory tools in other languages

Language CPU profiling Memory Notes
Go pprof built in: import _ "net/http/pprof", then go tool pprof -http=: http://host/debug/pprof/profile?seconds=30 heap, allocs, goroutine, block and mutex profiles; runtime/trace for scheduler traces Excellent first-party tooling; continuous profiling via Pyroscope or Parca
Rust perf + flamegraph (cargo flamegraph), samply, Instruments (macOS), VTune heaptrack, dhat-rs, bytehound; Valgrind tools Build with debug symbols in release ([profile.release] debug = true)
C / C++ perf, VTune, gperftools, Tracy (frame profiler) Valgrind (memcheck, massif), AddressSanitizer (-fsanitize=address: use-after-free, overflows), LeakSanitizer, heaptrack Sanitizers in CI catch memory bugs early
Zig perf, Tracy integration, Valgrind std.heap.DebugAllocator reports leaks and double frees with stack traces in debug builds Explicit allocators make attribution easy
C#/.NET dotnet-trace, dotnet-counters, PerfView, Visual Studio profiler dotnet-gcdump, dotnet-dump + SOS EventPipe is roughly .NET's JFR
Python py-spy (sampling, attaches with no code changes), cProfile, Scalene tracemalloc, memray Many hot spots live inside C extensions
Node.js --cpu-prof, Chrome DevTools, 0x, clinic.js Heap snapshots in DevTools —
Erlang/Elixir :fprof, :eprof, observer, recon Per-process memory in observer Process-level visibility
Any (Linux) perf, eBPF tools (bcc, bpftrace), continuous profilers (Parca, Pyroscope, Grafana) — System-wide view, including the kernel
Go
// Go: one import adds production profiling endpoints (protect them!)
import _ "net/http/pprof"
go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()
// $ go tool pprof -http=:8081 http://localhost:6060/debug/pprof/heap
// $ go test -bench=. -benchmem -cpuprofile cpu.out && go tool pprof cpu.out

Tuning in practice

A tuning checklist for JVM services

  1. Right-size the heap for the live set (chapter 40), -Xms = -Xmx, container percentages, OOM flags.
  2. Pick the collector for the SLO: G1 by default, generational ZGC for tight tail latency.
  3. Keep JFR on continuously with a rolling buffer, so you have data when incidents happen.
  4. Profile the slowest endpoints with async-profiler (CPU, wall and alloc) under realistic load.
  5. Cut allocation in hot paths: streaming JSON (Jackson streaming or Afterburner/Blackbird), avoid boxing, reuse compiled regexes and formatters (DateTimeFormatter is immutable and thread-safe, so make it static), parameterised logging.
  6. Fix I/O patterns first: N+1 queries, missing indexes, unbatched calls, pool sizes (chapter 49).
  7. Check contention: JFR JavaMonitorEnter events and lock profiles.
  8. Startup: CDS/AOT cache (-XX:AOTCache), Spring AOT, lazy initialisation where acceptable (chapter 47), or native image for serverless.
  9. Validate each change with a reproducible load test, and compare p50, p99, throughput, CPU and allocation rate.

Lab: the hardware and the JIT, measured

Run on JDK 21 on a 2-core machine, timings from the last of several rounds. Four experiments, each a reason why intuition about performance fails.

Experiment 1: cache lines

A 4096 × 4096 int array (64 MB) summed in two orders:

Java
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) s += g[i][j];    // row by row
for (int j = 0; j < n; j++) for (int i = 0; i < n; i++) s += g[i][j];    // column by column
Text
16M ints, 64 MB: row by row 14.9 ms | column by column 256.8 ms (17× slower)

Same additions, same data. Row by row reads memory sequentially: each 64-byte cache line brings in 16 ints, and the hardware prefetcher fetches the next lines before they're needed. Column by column jumps to a different row array for every element, so nearly every read misses the cache and waits on main memory (about 100 ns, Volume 1 chapter 7). Data structures that keep related values together (arrays, ArrayList, primitive arrays) are fast to scan; linked structures and arrays of scattered objects aren't.

Experiment 2: arrays of objects versus arrays of primitives

Summing the x field of 5 million points stored as an array of record P(double x, double y) (shuffled, as objects end up after a real program's allocations and updates) versus a plain double[]:

Text
sum x over 5M points: array of objects (shuffled) 84.1 ms | double[] 6.2 ms | equal true

14× slower with objects. The array of objects is an array of references; each element is a separate object somewhere on the heap, so the loop chases a pointer and probably misses the cache per element. The double[] is one contiguous block the CPU streams through, and the JIT can vectorise the sum. This "structure of arrays" layout is how analytics engines, game engines and numeric libraries store data; in backend code it matters for large in-memory computations (pricing, recommendations, aggregations). Project Valhalla's value classes aim to let arrays of small records be stored flat.

Experiment 3: escape analysis

Java
record P(double x, double y) {}
static double dist(int i) { P p = new P(i, i + 1); return Math.sqrt(p.x() * p.x() + p.y() * p.y()); }
// called 50 million times
Text
escape analysis on (default):    50M temporary records: 470 ms | GCs 0
escape analysis off:             50M temporary records: 513 ms | GCs 60

The P never leaves dist, so C2 replaced it with two local doubles (scalar replacement): no allocation, no garbage, no collections. With escape analysis turned off, the same code allocated 1.2 GB of short-lived objects and triggered 60 young collections. The time difference is small because young-generation allocation and collection of dead objects is very cheap, which is the real lesson: don't pool or cache small objects to "save allocation" in modern Java; it usually makes things slower by keeping objects alive into the old generation. Escape analysis works only when the method is inlined and the object doesn't escape to a field, a collection or another thread.

Experiment 4: the benchmark that measured nothing

Java
for (int i = 0; i < 50_000_000; i++) { double v = Math.sqrt(i) * 3.0; }            // result discarded
double s = 0; for (int i = 0; i < 50_000_000; i++) s += Math.sqrt(i) * 3.0;          // result used
Text
50M sqrt-and-multiply: result discarded 0.0 ms | result used 147 ms

The JIT saw that the first loop's result was never used and had no side effects, and deleted the loop. A hand-written benchmark that "proves" an approach is infinitely fast has usually measured this. (While writing this lab, an earlier version printed double[] 0.0 ms in experiment 2 for the same reason, until the sum was printed.) Hand-timed loops also mix interpreter, C1 and C2 phases and GC noise. JMH handles all of it: forked JVMs, warm-up iterations, a Blackhole that consumes results, and statistics:

Java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public double sqrt(Blackhole bh) { double s = 0; for (int i = 0; i < 1000; i++) s += Math.sqrt(i) * 3.0; return s; }

Try it yourself

  1. Repeat experiment 1 with a 1D array of size n×n indexed g[i * n + j]. Is it faster than int[][] row by row?
  2. Measure false sharing: two threads each incrementing their own volatile long field, with the fields adjacent and then padded 128 bytes apart (or annotated @jdk.internal.vm.annotation.Contended with -XX:-RestrictContended). On a machine with two physical cores you should see a large difference; on two hyperthreads of one core you may see none.
  3. Make experiment 3's P escape (store the last one in a static field) and check whether GCs return.
  4. Profile the Volume 3 MenuApi from the Start Here chapter under load with async-profiler and find the widest tower in the flame graph.

Revision sheet: memory and performance

Key ideas

  • Method: goal (latency percentile, throughput, memory budget) → measure → hypothesis → one change → measure; check I/O and external calls first; use the USE and RED methods for systems (Volume 9).
  • Object layout: 12-byte header (8 with compact headers), compressed 4-byte references under 32 GB heaps, 8-byte alignment; boxing and wrapper objects; collection overheads (HashMap.Node 32 bytes).
  • Allocation: TLAB bump-pointer allocation; escape analysis and scalar replacement; cheap young collection; avoid object pools for small objects.
  • Hardware: cache lines (64 B), prefetching, locality, branch prediction, false sharing (@Contended), NUMA; data-oriented layout (structure of arrays).
  • Strings: compact strings (Latin-1), deduplication (G1), interning cautions.
  • Measuring: JMH (forks, warm-up, Blackhole, modes), JFR and Mission Control, async-profiler flame graphs (CPU, allocation, lock, wall-clock), heap histograms and dumps (MAT), GC logs.
  • Tuning: heap sizing in containers (MaxRAMPercentage), GC choice by objective, -XX:+AlwaysPreTouch, AOT cache for startup, connection pools and thread pools sized from Little's law.

Numbers to remember

  • Lab: column-order traversal 17× slower; array of scattered objects 14× slower than double[]; escape analysis removed 60 GCs; an unused computation measured 0.0 ms.
  • Memory per element: int[] 4 B, List<Integer> about 20 B, HashMap<Integer,Integer> about 70 B.
  • Main-memory access about 100 ns vs L1 about 1 ns.

Pitfalls

  • Optimising without a goal or profile; micro-optimising code that isn't on the hot path.
  • Hand-rolled benchmarks (dead code, no warm-up, single run).
  • Boxed collections for large numeric data; huge object graphs as caches.
  • Memory leaks through static collections, listeners, ThreadLocals and unbounded caches.
  • Profiling an idle service, or only in development.

Glossary

  • TLAB: thread-local allocation buffer.
  • Scalar replacement: replacing a non-escaping object with its fields in registers.
  • False sharing: threads contending on one cache line through different variables.
  • Flame graph: stacked visualisation of sampled call stacks.
  • Heap dump: a snapshot of every object on the heap.
  • Little's law: concurrency = throughput × latency.