Heap Walking and Allocation Tracking: TLABs and Analysis
Understand how the JVM allocates memory with TLABs, how to track allocations with low overhead, and how heap walking tools analyze object graphs.
Understand how the JVM allocates memory with TLABs, how to track allocations with low overhead, and how heap walking tools analyze object graphs.
Heap Walking and Allocation Tracking: TLABs and Heap Analysis
Every Java object you create eventually lives on the heap, and understanding how and where those objects get allocated is critical for diagnosing memory issues. The JVM uses Thread-Local Allocation Buffers (TLABs) to make allocation fast and lock-free, but this also makes tracking allocation origins harder. This guide explains how TLABs work, how to use allocation profiling tools without destroying performance, and how to walk the heap graph when you need to find what is keeping your memory hostage.
Introduction
Every Java object you create lives on the heap, but the path it takes from your code to memory is more nuanced than a simple allocation call. The JVM uses Thread-Local Allocation Buffers (TLABs) to make allocation fast and lock-free, while sampling profilers report estimates instead of every allocation. Understanding how TLABs work, how to track allocations without destroying performance, and how to walk the object graph when things go wrong are essential skills for anyone diagnosing memory issues in production Java applications.
TLABs sit at the intersection of allocation performance and observability. They eliminate allocation contention in multi-threaded applications, but the fast pointer-bump path means sampling profilers cannot observe every object. To see allocation sites, use sampled profiling or JFR events; JVMTI offers both sampled events and lower-level agent APIs, each with different trade-offs. Meanwhile, heap walking answers a different question: not where objects are created, but why they are still alive and what is keeping them in memory.
This post covers TLAB mechanics and allocation tracking, then shifts to heap walking when you need to find retention leaks that allocation data cannot explain. You will learn when to reach for allocation profiling versus heap dumps, how to use async-profiler and JFR with bounded production captures, and how to trace GC root chains to find what is keeping your memory hostage. Practical failure scenarios show how sampling limits, retention leaks, and off-heap memory can point to different problems.
How the JVM Allocates Memory
Before getting into diagnostics, you need to understand how modern JVMs actually put objects on the heap.
The Problem with Concurrent Allocation
In a multi-threaded application, naively allocating objects on a shared heap requires synchronization. If every thread had to grab a lock to allocate memory, allocation would become a serious bottleneck. The JVM solves this with thread-local allocation buffers.
Before TLABs existed, the JVM used a global mutex protecting the heap’s free-list. Every new call had to acquire this lock, even though most allocations are small and short-lived. In a benchmark with 16 threads allocating strings, lock contention alone could account for 30-40% of CPU time spent in allocation.
The synchronization cost scales badly with thread count. A application with 32 cores allocating objects concurrently would spend more time waiting for the allocation lock than doing useful work. TLABs eliminate this bottleneck entirely by making the common case (allocating into thread-local memory) lock-free. The only time a thread interacts with shared state is when its TLAB is exhausted and it needs a new one from Eden.
The pre-TLAB allocation path looked like this: every new call walked the heap’s free-list to find a block large enough, updated list pointers (requiring the global mutex), and returned. Lock contention on the free-list mutex serialized what should have been independent operations across threads. A 1998 study of the Sun JVM found that mutex contention alone could consume 30-40% of CPU cycles in high-throughput server applications, and that figure worsens as core counts climb because more threads compete for the same lock.
Beyond mutex contention, cache coherence traffic made the problem worse. When Thread A held the allocation mutex and modified free-list pointers in L3 cache, every other thread trying to allocate had to invalidate and reload those cache lines. On a system with 16 or 32 cores, the cache thrashing around a single mutex line could cut effective memory bandwidth in half. The JVM needed a design where most allocations touched no shared data at all.
TLABs solved this by assigning each thread a private reservation in Eden. The thread allocates by incrementing a pointer into its reservation — a single write to thread-local memory that requires no synchronization. Only when the reservation runs out does the thread briefly interact with shared state (requesting a new TLAB from Eden). This converts a multi-threaded contention problem into a single-threaded bump operation for the common case, and the numbers reflect it: TLABs reduced per-object allocation cost from roughly 30 ns with locking to about 1-2 ns per allocation on modern hardware.
Thread-Local Allocation Buffers (TLABs)
TLABs are pre-allocated regions of Eden space that are assigned to each application thread. When a thread creates a new object, it allocates memory from its TLAB using a simple pointer bump — no locks, no atomic operations, just writing the object into the buffer and advancing a pointer.
graph TB
subgraph "Heap"
direction TB
subgraph "Eden Space"
T1[TLAB 1<br/>Thread-1]
T2[TLAB 2<br/>Thread-2]
T3[TLAB 3<br/>Thread-3]
end
subgraph "Survivor Spaces"
S1[S0]
S2[S1]
end
subgraph "Old Generation"
OG[Old Gen]
end
end
T1 -->|Fill, GC| S1
T2 -->|Fill, GC| S1
T3 -->|Fill, GC| S2
S1 -->|Aging| OG
S2 -->|Aging| OG
When a TLAB is exhausted, the thread requests a new one from Eden. This happens without stopping other threads.
What TLABs Mean for Profiling
Because allocation often happens inside a TLAB with a thread-local pointer bump, a profiler that samples stacks does not observe every object. Instrumenting allocation sites can capture more events, but changes the work being measured and may add overhead.
To see where allocations are coming from, use sampled allocation data. With JDK 25, JFR’s jdk.ObjectAllocationSample event records allocation samples with stacks; JVMTI’s SampledObjectAlloc notifies an agent about sampled objects, and the agent must collect any stack data it needs. async-profiler 4.6 also samples allocations using HotSpot-specific TLAB callbacks. These samples estimate allocation pressure; they are not exact counts of every object. VMObjectAlloc is not a callback for all allocations: the JDK 25 JVMTI specification excludes ordinary bytecode allocations such as new and JNI allocation calls. Exact object counts require targeted instrumentation of allocation sites, which can change the workload and add substantial overhead. Use that only in a controlled experiment.
Symptom-to-Tool Guide
| Symptom | Start with | What it answers |
|---|---|---|
| Allocation churn or frequent young collections | JDK 25 JFR allocation samples; use async-profiler 4.6 for an allocation flame graph | Which stacks account for sampled allocation pressure? Samples are estimates, not an exact object count. |
| Post-GC heap occupancy keeps rising | A JDK 25 heap dump from jcmd, then Eclipse MAT |
Which objects remain live, and which GC roots retain them? See heap dump analysis and Java heap structure. |
| Process RSS/native memory rises while Java heap stays flat | NMT, if enabled when the JVM started; check BufferPoolMXBean for direct buffers |
Is HotSpot’s tracked native memory growing? NMT does not cover third-party native allocations. |
When to Use Allocation Tracking
Ideal Use Cases
Allocation tracking answers one specific question: which code paths are creating the most objects right now? It is most useful in four scenarios.
Finding allocation hotspots is the most common use case. Allocation flame graphs show which call stacks produce the most objects per second. This helps you spot unintentional object creation in hot paths — string concatenation in a tight loop, defensive copying in a frequently-called method, logging that builds large strings on every invocation.
Memory leak investigation works with allocation tracking when the leak stems from excessive creation rather than failed cleanup. If your heap grows because millions of small objects are created and held onto, allocation profiles show where they originate. Combined with object age histograms from GC logs, you can see whether objects survive longer than expected.
GC tuning uses allocation tracking to understand which generations receive the most traffic. Compare JFR allocation samples with GC logs and heap summaries to see whether young-generation collections are frequent and what allocation stacks may contribute. High allocation pressure with objects dying quickly in Eden may point to a need to review the young-generation or TLAB settings.
JFR or profiler allocation samples help locate large allocation sites, but they do not provide a complete TLAB-versus-outside-TLAB census. Large objects can take a slow allocation path outside a TLAB; the exact behavior depends on the JVM and collector. Use heap and GC diagnostics to understand their impact before deciding whether a buffer or data structure belongs off heap.
Capacity planning also improves with allocation tracking. Watching allocation trends across releases shows whether your application allocates more or less over time, helping you predict memory needs before they become production problems.
When Allocation Tracking Misleads
Allocation tracking tells you where objects are born, but it has blind spots. Missing these leads to wasted effort optimizing the wrong thing.
Sampling is the biggest limitation. A profile can underrepresent short-lived objects because it records samples rather than each allocation. A profiler might show a modest allocation rate while young GC reclaims far more memory; compare the sample with GC logs instead of treating it as a complete tally. Allocation profiles do not measure heap turnover directly.
Sampling can miss rare bursts. A large batch operation—loading a dataset or parsing a file—may not appear clearly in a short capture. This matters when investigating OOM: a quiet profile does not prove that the workload has no allocation spikes.
Survivor confusion happens because allocation rate does not equal heap pressure. A churned survivor space still stresses GC even when new allocation rate looks low. Objects that survive young GC but die in survivor spaces still consume GC CPU time. GC logs show heap pressure from survived objects that allocation profiles cannot see.
When retention is the real problem, allocation tracking hits a wall. A cache with no eviction policy might show modest per-entry allocation rates — nothing alarming. But the retained heap grows indefinitely. Only heap dumps and GC root chain analysis reveal what is keeping those entries alive.
Implementation: Reading TLAB Statistics
import java.lang.management.*;
import javax.management.*;
public class TlabDiagnostics {
public void dumpTlabStats() {
List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean pool : pools) {
// TLAB stats are in the young generation pools
MemoryUsage usage = pool.getUsage();
if (usage == null) continue;
String name = pool.getName();
System.out.println("Pool: " + name + " used=" + usage.getUsed());
}
}
public void parseAllocationFromJfr(String jfrFile) throws Exception {
// Use JFR API to analyze allocation events
System.out.println("Analyzing allocation from " + jfrFile);
// jfr print --events jdk.ObjectAllocationSample file.jfr
}
}
Using async-profiler for Allocation Profiling
Use async-profiler 4.6 with a HotSpot JVM to sample allocation stacks. The --alloc value is a byte interval; 500k means roughly one sample per 500 KB allocated on average, not one sample for every 500,000 objects.
# async-profiler 4.6; run as the JVM's OS user
./asprof -e alloc --alloc 500k -d 60 -f alloc-profile.html <pid>
Allocation samples are weighted estimates of allocation pressure, not exact object counts. The exact overhead depends on workload and sampling interval, so begin with a short capture and watch CPU use and service latency. CPU profiling on Linux may need access allowed by the kernel’s perf_event policy; that permission is separate from allocation mode. -XX:MaxGCPauseMillis is a GC tuning option, not an async-profiler setting.
Using JFR for Allocation Samples
On JDK 25, start a short recording with the profile settings and print the allocation sample event:
# jcmd must run on the same host and as the JVM's effective OS user/group
jcmd <pid> JFR.start name=alloc settings=profile duration=60s filename=alloc.jfr
jfr print --events jdk.ObjectAllocationSample alloc.jfr
JFR’s profile settings collect more data and can add more overhead than default.jfc; keep the recording short and compare latency and CPU against your normal baseline. The jdk.ObjectAllocationSample events are samples, not a census. A JDK 25 JVMTI agent can also request SampledObjectAlloc; its specification uses a default sampling interval of 512 KB per thread. The separate VMObjectAlloc event does not report ordinary bytecode and JNI allocations, so it is not an exact object counter.
Heap Walking
Heap walking traverses object references to explain why objects remain live. Eclipse MAT performs this analysis on a heap dump; allocation profiling answers where sampled objects were created, not why they remain in memory.
GC Roots
Objects are kept alive by references from:
- Thread stacks: Local variables and operand stacks
- JNI references: Native code holding Java object references
- Static fields: Class-level object references
- Running threads: The thread object itself
- Classloaders: Classloader objects
- Finalization queue: Objects awaiting finalization
Using JHSDB for Postmortem Analysis
JHSDB is an experimental, unsupported Serviceability Agent tool in JDK 25. Do not use a live attach as a routine production profiler: Oracle documents that attaching to a live process causes it to hang and that it may crash when the debugger detaches. Prefer a heap dump for ordinary retention analysis. Use JHSDB on a core file in a controlled postmortem investigation, with the matching Java executable and JDK 25 tools:
# JDK 25; analyze a core dump, not a live production process
jhsdb jmap --exe "$JAVA_HOME/bin/java" --core core.dump
The Serviceability Agent can inspect HotSpot internals, but its output is version- and VM-specific. Keep the core file access-controlled because it can contain application data.
Programmatic Heap Walking with JVMTI
JDK 25 JVMTI exposes FollowReferences for traversing reachable objects and their references. An agent supplies a jvmtiHeapReferenceCallback using the signature in that JDK’s include/jvmti.h, then invokes the traversal from a VM-safe point:
// JDK 25 JVMTI; callback must use the jvmtiHeapReferenceCallback signature.
jvmtiHeapCallbacks callbacks = {0};
callbacks.heap_reference_callback = reference_callback;
jvmtiError err = (*jvmti)->FollowReferences(
jvmti, 0, NULL, NULL, &callbacks, user_data);
This API is for native JVMTI agents, not an application snippet that can run by itself. The agent must request the can_tag_objects capability before calling FollowReferences. Heap traversal can be costly and should be exercised against a representative staging process before production use. VMObjectAlloc is a separate JVMTI event and does not cover ordinary bytecode or JNI allocation calls, so do not use it as an exact object counter.
Production Failure Scenarios
Scenario 1: Allocation Rate Mismatch
Symptom: Your profiler shows low allocation rate but GC is constantly running.
Investigation: A sampling profile estimates allocation pressure at selected stacks; it does not count every allocation or measure how many bytes a collection reclaims. Short-lived objects can contribute substantial young-generation turnover even when a sampled profile looks modest.
What TLAB hiding looks like: A profiler might show 100MB/s of allocations, but young GC is reclaiming 2GB/s. The difference is short-lived objects that never get sampled.
Fix: Use GC logs or JFR’s garbage-collection and heap-summary events to understand collection activity. Compare that with allocation samples to locate likely churn, while treating the sampled rate as an estimate.
Scenario 2: Retention Leak Masked as Allocation Leak
Symptom: Heap grows but allocation profiling shows no obvious culprit.
Investigation: The problem is not how many objects you allocate, but how long they live. A cache with no eviction policy might allocate a modest number of entries but never release them.
Approach: Capture a heap dump with JDK 25 jcmd and analyze it with MAT to find the GC root chain keeping objects alive. Allocation profiling alone cannot find retention leaks.
# JDK 25: the dump can contain application secrets and may pause the JVM
jcmd <pid> GC.heap_dump heap.hprof
# Open heap.hprof in Eclipse MAT
Scenario 3: NIO DirectByteBuffer Appearing as Native Memory Leak
Symptom: Native memory (off-heap) grows continuously, heap looks fine.
Investigation: Direct ByteBuffer memory lives outside the Java heap. Check the direct buffer pool through BufferPoolMXBean; NMT reports HotSpot-managed native memory, not allocations made by JDK class libraries, JNI code, or third-party native libraries.
# JDK 25: enable NMT when starting the JVM (5-10% documented overhead)
java -XX:NativeMemoryTracking=summary -jar app.jar
# Later, compare HotSpot's native-memory totals
jcmd <pid> VM.native_memory baseline
# ... run workload ...
jcmd <pid> VM.native_memory summary.diff
# For allocation call sites, use detail instead of summary at JVM startup.
NMT diffs help explain HotSpot’s tracked categories. If RSS grows while NMT stays flat, investigate direct buffers with BufferPoolMXBean and use platform-specific native-memory tools for JNI or third-party allocations.
Trade-off Table
| Aspect | JDK 25 JFR profile |
async-profiler 4.6 alloc |
JDK 25 jcmd heap dump |
JDK 25 NMT |
|---|---|---|---|---|
| Data captured | Sampled allocation and other enabled events | Sampled allocation stacks | Snapshot of reachable heap and references | HotSpot native-memory categories and call sites |
| Exact object counts | No | No | Snapshot counts by class, not allocation history | No |
| Overhead | Depends on enabled events; profile can cost more than default.jfc |
Depends on workload and sample interval | Can pause the JVM and needs disk space proportional to the dump | 5-10% documented overhead; enabled at JVM startup |
| Production use | Short, monitored captures | Short, monitored captures | Only with an incident plan, impact budget, and protected storage | Enable only when the documented overhead is acceptable |
| Shows retention | No | No | Yes, analyze with MAT | No |
| Limits | Samples estimate allocation pressure | Samples estimate allocation pressure | Contains sensitive process data | Does not track third-party native allocations or JDK class-library allocations |
Observability Checklist
- Use JDK 25 JFR
jdk.ObjectAllocationSampleor async-profiler 4.6--allocfor sampled allocation stacks - Treat allocation samples as estimates, not exact object counts
- Correlate allocation rate with GC logs — mismatch reveals TLAB hiding
- Capture a JDK 25 heap dump with
jcmdonly when the pause, disk use, and data sensitivity are acceptable - Track direct-buffer usage with
BufferPoolMXBean; use NMT for HotSpot-managed memory only - Set a short profiling window and watch service latency and CPU while capturing
- Grant diagnostic access to the JVM’s OS user or an approved operator; keep output files access-controlled
- Track heap occupancy over time with
MemoryMXBeanto find gradual leaks - For live retention analysis, prefer a planned heap dump; reserve JHSDB for core-file postmortems
Security Notes
Allocation data can expose sensitive information:
- Allocation call stacks reveal business logic, API endpoints, and data structures
- Heap dumps contain full application state including session data, tokens, and PII
- Allocation profiling data stored in files may be accessible to unauthorized users
Best practices:
- Take heap dumps only in staging or with explicit approval in production
- Store heap dumps in encrypted storage with access controls
- Limit heap-dump and JFR output directories by owner, permissions, and disk quota; remove files after analysis
- Cleanse sensitive data from allocation logs before sharing
- Restrict access to allocation flame graph outputs
- Use temporary files for profiling data that are deleted after analysis
Common Pitfalls / Anti-Patterns
Pitfall 1: Confusing Allocation Rate with Heap Pressure
Problem: You optimize the top allocation sites, but heap still grows.
Explanation: Allocation profiling shows where objects are created, not how long they live. Reducing allocations that die young in Eden does not reduce old generation pressure. You need to find retention, not allocation.
The disconnect is real: allocation profiling tallies bytes written to the heap per second, while GC logs report bytes reclaimed per second. In a healthy application with short-lived objects, allocation rate might show 500MB/s while young GC reclaims 2GB/s — objects that lived for milliseconds inside Eden and never stressed old generation. Optimizing the allocation hotspot does nothing for those objects because they were already dying in Eden.
In practice, this is how it shows up. Developers profile a memory leak, see the biggest allocation sites are byte[] arrays or String buffers in hot loops, optimize those paths, cut allocation rate by 40%, and the heap still grows. The leak is not in allocation — it is in retention. Somewhere a ConcurrentHashMap used as a cache has no eviction policy, or a listener list keeps growing, or a static ThreadLocal holds references that only get cleared when the thread dies. GC logs and heap histograms surface this pattern: survivor space churn tells you objects are aging up instead of dying, and heap dumps show retained collections growing over time.
Fix: Use heap dumps and GC logs together. GC logs show where memory is actually being retained — look for increasing old generation occupancy despite reasonable allocation rates. Heap histograms taken at two points in time show which classes are growing. The combination points to retention problems that allocation profiles cannot see.
Pitfall 2: Sampling Too Coarsely
Problem: Rare allocations that cause OOM never appear in profiles.
Explanation: A sampled profile can miss allocations from an infrequent batch operation, such as loading a large dataset once.
Sampling profilers interrupt your application at regular intervals, walk the call stack, and record what the thread was doing. If a thread is parsing a 500MB JSON file and allocating millions of temporary objects, but no sample fires during that operation, those allocations are invisible. A single large batch allocation can dwarf thousands of small allocations in heap pressure while being completely absent from allocation flame graphs.
This matters when OOM crashes seem inexplicable. A short capture under normal load may miss a large batch operation at peak traffic, such as importing a report or warming up a cache. A quiet sampled profile does not rule out short-lived bursts or small allocations that together create substantial pressure.
Sampling bias also distorts the apparent distribution by type. You see frequent small allocations clearly but miss infrequent large ones. Heap dumps show the opposite — large objects dominate the histogram — so you might conclude a large cache entry is the culprit when it is actually a million small objects that were never sampled.
Fix: When investigating OOM, do not rely on allocation samples alone. Use JDK 25 jcmd <pid> GC.class_histogram for a class-level snapshot or capture a heap dump when retention paths are needed. For allocation profiles, set async-profiler 4.6’s byte interval with --alloc and use realistic peak load, while monitoring CPU and latency.
Pitfall 3: Ignoring DirectByteBuffer Off-Heap Memory
Problem: Java heap looks fine but OS reports the process using far more memory.
Explanation: Direct ByteBuffer and other off-heap allocations do not appear in Java heap metrics.
DirectByteBuffer is the most common source of off-heap memory leaks in Java applications that do file or network I/O. When you create a FileChannel.map() region or call ByteBuffer.allocateDirect(), the JVM allocates native memory outside the Java heap. The operating system tracks this as part of your process, but Runtime.maxMemory() does not see it and heap histograms do not show it. The DirectByteBuffer object on the Java heap is tiny — just a few dozen bytes — but it holds a pointer to a native memory region that can be hundreds of megabytes.
Cleanup depends on garbage collection. When a DirectByteBuffer becomes unreachable, the GC discovers it during a young GC cycle and adds it to the cleaner queue. A dedicated cleaner thread then frees the native memory. If your application creates DirectByteBuffers faster than GC can finalize them, or if the cleaner thread falls behind, native memory grows faster than the Java heap. Under high I/O load with large buffers, you can accumulate gigabytes of off-heap memory while the Java heap stays well within its limits. The OS reports RSS far exceeding -Xmx.
The Java heap shows only the small DirectByteBuffer wrapper, not its native payload. Heap dumps can help explain which Java references keep wrappers alive, but they do not show the native allocation’s size. NMT also does not track JDK class-library allocations, so use BufferPoolMXBean and platform-specific native-memory tools to investigate direct-buffer growth.
Fix: If NMT was enabled when the JVM started, take a baseline with jcmd <pid> VM.native_memory baseline and compare summary or detail diffs. Treat it as a view of HotSpot-managed memory, not a direct-buffer or JNI allocation tracker. For direct buffers, monitor BufferPoolMXBean; for unexplained native growth outside NMT, use platform-specific native-memory tools. Do not call internal cleaner APIs to force cleanup.
Pitfall 4: Misreading GC Root Chains
Problem: Heap dump analysis shows a massive object as the leak suspect, but it is just a symptom.
Explanation: MAT-style tools show the path keeping the largest object alive. But that object might itself be referenced by something bigger. You need to walk backwards from the GC root, not forwards from the largest object.
The “largest object” in a heap dump is almost never the root cause of a memory leak — it is the symptom. A HashMap with a million entries is large because something is putting entries in it. The HashMap is not the problem; whatever is filling it is. The biggest object tells you what is consuming memory, not why. GC root chain analysis tells you what is keeping it alive, which is what you actually need to fix.
MAT’s “Path to GC Roots” follows incoming references — all the objects that hold a direct or indirect reference to your target. Trace backward from the largest object and you eventually hit a GC root: a static field, a thread-local, a classloader, or something in a finalization queue. That GC root is your leak cause. Go forward instead (following outgoing references) and you are exploring the object’s internal structure, which tells you nothing about why it cannot be collected.
The misread I see most often is treating a ConcurrentHashMap as the leak suspect because it is the largest object in the histogram. The real issue is usually that the map has no eviction policy, so entries accumulate. Or the entries are referenced by a singleton that never gets cleared. You spend weeks investigating the HashMap implementation when you should be investigating who is adding entries and why eviction is not keeping up.
Weak references add another layer of confusion. WeakHashMap entries disappear on GC, so they do not prevent leaks — but ConcurrentHashMap used as a cache with strong references does. Running “Path to GC Roots” with “exclude weak refs” shows only references that are actually keeping objects alive. If the chain goes through a WeakReference, that reference is not your leak.
Fix: Use “Path to GC Roots” in MAT, selecting “exclude weak refs” to see what is really pinning memory. Always ask what is keeping the chain going — not what the largest object contains, but what is pointing to it. Trace the chain until you hit a GC root and then investigate that root’s lifecycle.
Pitfall 5: TLAB Sizes Changing Under Load
Problem: Allocation profile changes dramatically between idle and peak load.
Explanation: TLAB sizes are dynamically computed based on allocation rate and thread count. When load changes, TLAB sizes change, which changes what appears in allocation profiles.
HotSpot adjusts TLAB sizes as the application runs. This can change allocation-event frequency under different workloads, so compare captures under similar load and use GC metrics to understand total heap turnover.
Under different loads, TLAB sizing and allocation patterns can change. A sampled profile may shift even when the code has not, so avoid reading percentages as exact per-site object counts.
JFR’s jdk.ObjectAllocationSample and async-profiler’s allocation mode report samples, not every object. -XX:MaxGCPauseMillis is a GC tuning option; it does not set async-profiler’s sampling interval. In async-profiler 4.6, use --alloc to set the allocation sampling interval in bytes.
Comparing allocation profiles from different load levels is unreliable. A code path that appears more allocation-intensive in one profile might just reflect different TLAB sizes, not actual behavior change. Profiles taken under load A are not directly comparable to profiles taken under load B unless the loads produce similar TLAB sizes.
Fix: Run allocation profiling under realistic load to match production conditions. If you are comparing profiles across releases, keep the workload and thread count similar. Treat sampled percentages as estimates and correlate profiles with GC logs to confirm how much memory the collector processes.
Quick Recap Checklist
- TLABs make the common allocation path fast, while allocation profiles remain samples
- Allocation profiles estimate allocation pressure; they do not give exact object counts
- Use JDK 25 JFR
jdk.ObjectAllocationSampleor async-profiler 4.6--allocto find sampled allocation stacks - Keep production captures short and monitor latency and CPU
- Retention leaks require heap dumps, not allocation profiling
- NMT reports HotSpot-managed native memory; use
BufferPoolMXBeanfor direct buffers - GC logs show actual heap pressure; allocation profiles show where objects originate
- Use JDK 25
jcmdfor heap dumps, with an impact and data-handling plan - Heap dump analysis with MAT requires understanding GC root chains
- Stop a capture if CPU use or service latency crosses the approved diagnostic budget
Interview Questions
A TLAB (Thread-Local Allocation Buffer) is a region of Eden reserved for one application thread. The common allocation path advances a thread-local pointer, avoiding shared synchronization. Allocation profilers therefore rely on sampling or JVM events instead of observing each pointer bump. On JDK 25, JFR's jdk.ObjectAllocationSample event records allocation samples; those samples estimate pressure and are not exact object counts.
Allocation profiling tells you where objects are born. A retention leak is about where objects die — or rather, why they keep living when they should not. To find retention leaks, take a heap dump and analyze it with MAT or similar tools. Look at the largest objects first, then trace their GC root chains using "Path to GC Roots" (excluding weak references). You are looking for unexpected references keeping collections, caches, or stateful objects alive long past their useful life. Common culprits are: maps used as caches without eviction, listeners registered but never unregistered, static collections accumulating entries, and objects stored in ThreadLocal that outlive their thread.
Allocation profiling estimates which call sites account for allocation pressure; sampled tools do not count every object. It answers "where are objects being created?" Heap walking traverses references among live objects and answers "why is this object still alive?" A JDK 25 heap dump can pause the application and needs storage, so capture it only when the operational impact and data handling are acceptable.
In async-profiler 4.6, allocation mode uses HotSpot-specific TLAB-driven sampling to associate sampled allocated bytes with call stacks. Set the allocation interval with --alloc, such as --alloc 500k for roughly one sample per 500 KB allocated on average. This is a statistical profile, not an exact object count; measure its CPU and latency impact on the target workload.
Java heap is one part of a JVM process's memory footprint. With JDK 25, NMT reports HotSpot-managed native-memory categories when enabled at JVM startup with -XX:NativeMemoryTracking=summary or detail; Oracle documents 5-10% overhead. NMT does not track third-party native code or JDK class-library allocations. Check direct-buffer usage through BufferPoolMXBean, and use platform-specific tools to investigate native allocations outside NMT.
TLAB size is computed dynamically based on several factors: the allocation rate of the thread (higher allocation rate = larger TLAB), the desired refill waste threshold (typically 2%), and the overall Eden size and thread count. The JVM calculates desiredTLABSize = AllocationRate / TargetAllocationRate * averageTLABSize. When allocation rate spikes, TLABs grow larger to reduce TLAB refill overhead. When a thread dies, its TLAB is abandoned and its remaining space is reclaimed. You can control minimum and maximum TLAB sizes with -XX:MinTLABSize and -XX:TLABSize, but the JVM may override these based on observed allocation behavior.
Some allocations take a slow path outside a thread's TLAB, including sufficiently large objects. The exact threshold and collector behavior depend on the JVM and collector; a large allocation is not necessarily a G1 humongous allocation. JFR allocation samples can help identify stacks associated with allocation pressure, but they do not provide an exact count of every object.
G1 (Garbage First) uses a different heap layout than Parallel GC — it divides the heap into many small regions instead of contiguous Eden/Survivor/Old spaces. TLABs still exist within G1's Eden regions, but G1's incremental collection approach means TLAB waste has different implications. G1 can reclaim a TLAB's remaining space more efficiently because it only collects regions that are mostly empty, whereas Parallel GC must collect entire generations. G1 also has a "humongous region" concept for objects larger than 50% of a region size, which behave differently from standard TLAB allocations.
Collector choice can affect allocation paths and the operational cost of a heap inspection. Do not assume a JVMTI heap traversal is pause-free with ZGC: JDK 25's FollowReferences traverses the reachable reference graph and should be tested on a representative workload. Use a heap dump and supported analysis workflow when you need retention paths.
Escape analysis determines whether an object escapes a method's scope (e.g., returned, stored in a collection, or passed to another thread). When an object does not escape, the JIT can allocate it on the stack instead of the heap — this is called "scalar replacement." Stack allocation means the object never appears in heap profiles or heap dumps. This is why sometimes you see fewer allocations in profiles than expected for well-optimized code. The interaction with TLABs is indirect: scalar replaced objects bypass TLAB allocation entirely since they never touch the heap. Understanding this helps explain discrepancies between allocation profiling and GC logs.
Use the JDK 25 diagnostic command jcmd <pid> GC.heap_dump heap.hprof to write a heap dump in HPROF format, then open it in a tool such as Eclipse MAT. A heap dump captures sensitive process data, can require substantial disk space, and can pause the application; plan the capture and secure the file. Use jcmd <pid> GC.class_histogram when a class histogram is enough.
Shallow heap is the size of the object itself (just the object header plus field sizes). Retained heap is the total size of the object plus all objects it keeps alive through direct or indirect references. In MAT, the "shallow size" of a HashMap is just the HashMap object size (~56 bytes), while its "retained size" includes the HashMap object plus all Entry objects plus all key-value objects reachable from those entries. Retention leaks cause retained heap to grow while shallow heap stays small. When analyzing dumps, always look at retained size — a large shallow heap object might not be the leak if it only points to small objects.
Card marking is how the JVM tracks which regions of memory might contain references to older generations. The heap is divided into "cards" (typically 512 bytes). When a TLAB is filled and a pointer to an older object is stored, the card containing that pointer is marked "dirty." During young GC, only dirty cards need to be scanned for cross-generational references instead of the entire heap. This is critical for G1's incremental collection. Excessive card dirtying from frequent TLAB-to-old-gen references can cause GC performance issues — a pattern common in applications with large write-heavy caches.
Objects with a finalize() method are not reclaimed immediately when unreachable — they are placed in the finalization queue and finalized by a dedicated thread before being reclaimed. During this time, the object is still alive (retained in heap) even though it is effectively dead. MemoryMXBean.getObjectPendingFinalizationCount() tells you how many objects are waiting for finalization. Large numbers of objects pending finalization indicate finalizer threads are overwhelmed or finalizers are slow. This is a common source of memory leaks because objects that should die quickly accumulate until the finalizer runs. Using try-finally or Cleaner (Java 9+) is preferred over finalization.
When large objects appear in the leak suspect list, trace their inbound references backward (not forward) using "Path to GC Roots" in MAT. The pattern to look for: the large object is a container (List, Map, cache) and its size reflects accumulated entries. If the container itself appears in the leak list, find what is keeping it alive — usually a static reference, a singleton cache, or a thread-local map. If the large object is a byte array or DirectByteBuffer, the leak is likely in NIO buffer management or native memory. Check the GC roots to see if it is reachable from thread stacks, static fields, or classloader hierarchies.
Weak references (WeakHashMap, WeakReference) are collected on the next GC cycle if only weakly reachable — they do not prevent garbage collection. Soft references are collected only when the JVM is low on memory, making them suitable for memory-sensitive caches. Phantom references are enqueued after an object is finalized but before its memory is reclaimed — used for post-mortem cleanup. For leak analysis, weak references in caches are a common culprit: entries disappear from the map after GC runs, making the cache appear to leak when the real issue is the map holding references to objects that should be weakly-referenced.
async-profiler 4.6's allocation interval is configured in bytes with --alloc; for example, --alloc 500k samples about once per 500 KB allocated on average. The -i option controls an event interval and is not the allocation-byte interval. The result is a sampled estimate, so compare it with GC metrics rather than treating the profile as an exact object count.
Object alignment (controlled by -XX:ObjectAlignmentInBytes, default 8 bytes) ensures objects start at addresses that are multiples of this value. This affects both object size (padded to alignment) and TLAB sizing (TLAB size must be a multiple of alignment). Larger alignment reduces fragmentation and can improve performance on architectures with efficient vector operations, but increases memory overhead (a 17-byte object becomes 24 bytes with 8-byte alignment). TLAB sizing algorithms use alignment to ensure TLAB boundaries align with object boundaries, preventing wasted space from cross-TLAB allocations.
The dead code trap occurs when you optimize allocation sites based on profiling data that includes code paths that are no longer executed in production (e.g., debugging code, feature flags, or dead branches after refactoring). This makes the allocation profile misleading — you spend effort optimizing code that does not matter. To avoid it: verify allocation hotspots against production traffic patterns, use production traffic for profiling rather than synthetic benchmarks, and re-profile after code changes that remove or add allocation-heavy paths.
A JDK 25 jcmd <pid> GC.heap_dump heap.hprof command creates an HPROF heap snapshot and may pause the application while writing it. Check available disk space, arrange access-controlled storage, and plan for the pause before capturing in production. The dump contains application state; protect and remove it according to your incident-data policy. JHSDB live attach is not an alternative: Oracle documents that it hangs the process and may crash on detach.
Further Reading
- Advanced Java & JVM Internals Roadmap — Parent roadmap covering all JVM internals topics
- JVMTI Agents — Native agents that implement heap walking via JVMTI
- Heap dump analysis — Analyze heap snapshots and trace retention paths
- Java heap structure — Review JVM heap regions and object layout
- async-profiler 4.6 allocation profiling — TLAB-driven sampled allocation profiles and interval options
- JDK 25 diagnostic tools — JFR recordings and heap dump commands
- JDK 25 JHSDB command — Supported postmortem modes and live-attach warning
- JDK 25 JVMTI specification —
SampledObjectAlloc,VMObjectAlloc, andFollowReferences - JDK 25 Native Memory Tracking — Coverage limits, startup options, and documented overhead
- Eclipse MAT Documentation — Memory Analyzer Tool for heap dump analysis
- Baeldung: TLAB and Allocation — How TLABs work and affect profiling visibility
Conclusion
The key to effective heap analysis is picking the right tool for the question you are asking. Allocation profiling tells you where objects are born — useful for finding churn hot spots — while heap walking tells you why objects are still alive — essential for finding retention leaks. TLABs keep allocation fast and lock-free but add complexity when profiling. For production diagnostics, use JFR allocation events or async-profiler; for deep retention analysis, plan for heap dumps during maintenance windows and use MAT to trace GC root chains.
Category
Related Posts
CDS and AppCDS: Class Data Sharing for Faster JVM Startup
Learn how JVM Class Data Sharing works, create an AppCDS archive with Oracle JDK 21, and benchmark startup on your own workload.
JVM in Containers: Cgroup Memory Limits and Heap Sizing
A guide to how the JVM detects container memory limits, configures heap accordingly, and avoids pitfalls when running Java in Docker and Kubernetes.
GC Logging Analysis: Decoding JVM Garbage Collection Logs
Master JVM garbage collection log analysis with -Xlog:gc, GCEasy, and GCViewer. Practical guide to diagnosing memory issues and tuning performance.