JVM Object Allocation Deep Dive: TLAB, Escape Analysis & Scalar Replacement
This article explores JVM object allocation mechanisms including TLAB fast-path allocation, escape analysis with its three escape states, scalar replacement and lock elision optimizations, allocation rate as the primary driver of GC frequency, six common production allocation sources, and practical JFR profiling techniques for allocation governance.
Introduction
The previous four articles covered object death — how objects are judged dead and collected. This article flips the perspective to object birth: where a new object goes, how fast it is born, and which objects never need to be born at all. Allocation is the most overlooked link, yet it is the primary factor of GC frequency — Minor GC frequency ≈ allocation rate × average survival time ÷ Eden size. The earlier articles tuned the denominator and survival; this article tunes the numerator. After reading, you should be able to answer three production questions: why TLAB achieves allocation in tens of nanoseconds, what escape analysis actually saves, and why log string concatenation becomes the top GC fuel.
Three Production Incidents
Incident 1: Minor GC Every Two Seconds Deemed "Normal"
An order query service with a 4 GB heap and default G1 parameters suffered Minor GC every 2 seconds. RegionSize and pause targets checked out per Article 04. JFR allocation profiling revealed 73% of allocations came from a single line of "log object serialization" — DEBUG level was off, but parameter objects were still concatenated into large strings and passed to the logging framework. Changing the log to lazy evaluation reduced Minor GC frequency to 1.4 times per minute. Lesson: when GC is frequent, check allocation rate first, then tune GC parameters.
Incident 2: Betting on Scalar Replacement and Losing
A developer read that escape analysis lets local objects avoid the heap, so they placed a DTO construction inside a hot loop, trusting JIT to optimize. Under load, that method contributed 40% of allocations. Root cause: the method was too long, the loop body wasn't inlined, so the object was deemed method-escaping and scalar replacement didn't kick in. Escape analysis is a JIT discretion, not a contract — treating "non-escaping style" as a habit is fine, but relying on it as a dependency is not.
Incident 3: Regex Compilation as GC Fuel
A risk rule engine called Pattern.compile for a dynamic rule on every request, then matched. Allocation profiling showed Pattern/Matcher objects accounted for 18%, plus many CharBuffer intermediates. Switching to "pre-compile cache + invalidate on rule change" cut Minor GC frequency by 60%. Writing compile inside a method is a classic Java code review red flag — each call triggers a full parse + allocation.
These three incidents are three facets of the same model: when GC frequency is abnormal, first look at the numerator (allocation rate and sources), then the denominator (Eden/Region), and only then touch collector parameters — the troubleshooting order is the writing order of this article. A mnemonic: frequency anomaly → check rate; rate anomaly → check sources; source anomaly → fix code. Only after all three steps fail do you reach for the parameter toolbox from Articles 03–05. Most "GC problems" are solved at step two — because most GC problems aren't GC problems at all.
Technical Analysis: How Objects Are Born
1.1 Four Allocation Paths
new Foo()in JIT's view is a decision chain (Figure 1): the ideal is scalar replacement — when the object doesn't escape, it's broken into local variables and never enters the heap; next is TLAB fast allocation — the thread bumps a pointer in its private chunk, taking tens of nanoseconds, the path for 99% of objects; when TLAB is exhausted, the slow path (refill or lock Eden) is taken; objects larger than TLAB size take the off-heap slow path — in G1 they go straight to humongous regions (connecting to Article 04's Humongous). The priority of these four paths is the optimization order: first make objects not enter the heap, then make heap allocation fast enough.
Recalling Article 02's "object three-part layout": regardless of the heap path, the allocated content is identical — carve a memory block by object size, fill the object header (Mark Word + klass pointer), align if needed. The difference lies only in "where this memory comes from and whether locking is needed." Article 02 covered the divide between bump-the-pointer and free-list: TLAB/Eden are compact, a pointer bump finishes; CMS old generation is fragmented, allocation must search a free list. This is also the root cause of "young generation allocation fast, old generation allocation slow," and CMS-era allocation slowness was part of the fragmentation cost.
The four paths also share a cross-cutting perspective: each level matches cost to "object lifetime expectation." Scalar replacement serves ephemeral temporary objects (most common); TLAB serves ordinary heap objects; humongous regions serve long-lived large objects spanning collection cycles. When coding, if you have an expectation of "how long this object will live," you can reverse-check whether you've made long-lived objects frequent flyers on the short-lived path — e.g., putting a large byte[] cache in request scope mismatches both allocation path and lifetime, and the GC curve will immediately show the pain.
Another perspective is the "allocation pressure conduction chain": allocation rate doesn't just affect Minor GC frequency; it conducts layer by layer — high rate → Eden drains fast → survivor object ratio shifts → dynamic age threshold triggers easier → promotion accelerates → old gen pressure rises → Mixed and Full GC frequency rises. The promotion storms of Article 03 and Mixed backlogs of Article 04 often have their first cause on the allocation side. So this article isn't an epilogue after the three collector articles; it supplies the "cause" to the previous three's "effect" — looking back at those incidents, allocation governance is often the earliest step that should have been taken.
1.2 TLAB: The Art of Pre-Reserving Land
TLAB (Thread-Local Allocation Buffer, Figure 2) is a private slice of Eden carved for each thread, defaulting to ~1% of Eden and dynamically adjusted by allocation rate. It solves the "multiple threads contending for the same Eden" concurrency problem: instead of letting all threads lock to divide Eden, pre-assign each a private plot where they bump pointers. The allocation action is pure pointer arithmetic: new_top = top + obj_size, bounds check top+size vs end — two instructions on hit: lock-free, no search, no contention, speed on par with stack allocation.
Three concepts in TLAB's ledger are easily misread. waste : the tail fragment that can't fit the current object plus the unused remainder when GC arrives — they don't "move away," they just get invalidated with GC; waste rate is typically <5%, a designed-in cost, not a problem. refill : switching to a new block when the current one is exhausted — one of the slow paths, occasional in normal service. resize : JVM adjusts each thread's TLAB size based on actual allocation rate — fast allocators get big blocks, slow ones get small blocks, balancing refill frequency across threads. No need to manually tune TLAB parameters; the need is to understand why it exists.
TLAB also explains a detail buried in Article 02: why TLAB allocation can omit "zero initialization." Object header and field initialization happen on the memory carved from TLAB, and JIT can prove this memory hasn't been seen by other threads (reference not yet published), so initialization can be deferred or merged with writes — again premised on "non-escaping." One layer deeper: from allocation to initialization to scalar replacement, the three words "non-escaping" run through most of the allocation subsystem's optimization space — which is why this article places EA at the core.
1.3 Escape Analysis: Can Outsiders See the Object?
Escape Analysis (Escape Analysis, Figure 3) is a C2 compiler "data-flow audit": after method inlining completes , it checks each newly created object's reference flow — if the reference never flows out of the method (not assigned to fields, static variables, array elements, not returned, not passed to non-inlined methods, not captured by exceptions or synchronization), the object is "non-escaping" and two aggressive optimizations become possible: scalar replacement (allocation disappears) and lock elision (synchronization disappears) . Objects passed as arguments or returned ("method escape") have a chance to be downgraded to non-escaping after inlining — which is why inlining quality directly determines EA gains; objects assigned to fields or crossing threads ("global escape") cannot be optimized and must go to the heap.
Three misconceptions must be corrected. First, "stack allocation" has never been implemented in HotSpot — textbooks often say non-escaping objects are allocated on the stack; the actual implementation is scalar replacement: the object is "disassembled" into scalars (int, reference) that participate directly in computation, achieving the same effect but via a different mechanism. Second, EA is a probabilistic optimization : it only exists in C2 (interpreter and C1 don't have it), and inlining failure invalidates it — it cannot be treated as a contract; Incident 2 is the textbook case. Third, escape determination is per-method : an originally non-escaping object becomes globally escaping the moment it's passed to a non-inlined method — so "hot methods small and straight" isn't just readability; it's an engineering tactic to preserve EA gains.
An "EA friendliness" self-check lens: take your hottest method and ask three questions — Is it small enough? (bytecode <325 bytes for inlining chance, Article 08 gives exact thresholds); Does it call methods with unexpected boundaries? (reflection, dynamic proxies, virtual methods with multiple implementations break inlining); Where does its new object go farthest? (local is optimal). Three "no" answers mean EA gains are out of reach — this isn't the JVM's fault, it's the method shape's fault. "Method shape" is a new dimension this article adds to the code review checklist.
1.4 Scalar Replacement & Lock Elision: Before/After View
Figure 4 shows a concrete before/after: two locally constructed objects + one local lock, after EA become four int pure computations + lock-free code — allocation, object header writes, GC tracking, lock overhead all vanish, semantics fully equivalent. Verification is simple: run once default, watch jstat Eden barely grow; add -XX:-DoEscapeAnalysis and rerun, watch Eden skyrocket — the two curves are direct evidence of EA's existence. JFR's allocation profile is another clue: objects caught by scalar replacement don't appear on the leaderboard; turn off EA and they surface.
Lock Elision is EA's side benefit: if a lock object doesn't escape, its critical section can only be executed by the current thread, so synchronization is deleted outright. In practice it silently saves the day for implicit synchronization on local StringBuffer /collections — those synchronized -decorated local objects, in JIT's eyes, have their pretend overhead cleaned up. But note the direction: lock elision rescues "locks with no actual contention," not a license to write redundant synchronization ; locks on shared state are never touched by any JIT.
1.5 Allocation Rate: The Primary Factor of GC Frequency
The formula: Minor GC frequency ≈ allocation rate × average survival time ÷ Eden size. Previous articles tuned the denominator (Eden/Region size) and survival (promotion, Survivor); this article attacks the numerator. Allocation rate observation has two calibers: GC logs give "Eden usage difference between two Minor GCs ÷ time" → MB/s; JFR allocation profile gives "bytes allocated aggregated by stack frame" — the former quantifies total rate, the latter qualifies source distribution, the two calibers together form a complete allocation profile. Healthy online service allocation rate reference range: 200–800 MB/s per core is normal; GB/s level almost always has governance headroom (values vary by business, trend matters more than absolute).
Allocation rate also explains a frequent puzzle: why does increasing heap reduce Minor GC frequency but increase CPU usage? Larger Eden dilutes GC frequency, but allocation rate unchanged — each Minor GC scans a larger surviving object set (survival time × allocation rate), so single pause gets longer. The root cure is always in the numerator: same functionality, fewer allocations. That's why this article puts "govern allocation" before all GC parameters — it's the only lever that simultaneously improves frequency, pause, and throughput.
Allocation rate has an easily overlooked "hidden channel": thread creation. Every thread creation brings a ThreadLocal table, first TLAB, stack-adjacent objects — a small allocation pulse. High thread-creation services show regular sawtooth allocation curves uncorrelated with traffic shape. See sawtooth → check thread pools and scheduled tasks first, then business code — thread pool necessity gains another argument here. Observed values decoupled from traffic are forever the signal of "system-level allocation": threads, class loading, reflection proxies, not business objects.
1.6 Six High-Frequency Allocation Sources
Figure 5 lists six common sources in production allocation profiles. Log concatenation perennially tops charts: even with DEBUG off, log.debug(json.serialize(dto)) arguments are eagerly evaluated — correct approach is lazy evaluation or guards. Regex Pattern : compile inside a method equals full parse per request. Serialization intermediates : JSON deserialization intermediate trees on hot paths can occupy 20%. The rest: stream API intermediate collections, boxing & container resizing, exception construction — each has corresponding coding discipline. Governance priority sorted by "allocation bytes share × call frequency"; fixing the top two usually yields immediate GC curve improvement.
One special source deserves separate mention: framework/library "invisible allocations." Spring's per-request parameter parsing, AOP proxies, transaction templates have fixed allocations (design cost, usually not worth touching); the real danger is usage-layer amplification — e.g., calling a third-party utility that creates a new ObjectMapper every iteration in a hot loop, or putting large objects into stream chains for repeated transit. The remedy for invisible allocations isn't changing the framework; it's using the allocation profile to find "the point where our code calls it" and caching/reusing at the call site.
Governance actions also need "cost-effectiveness sorting" discipline: single-line code changes (lazy logging, static Pattern , Mapper reuse) take precedence over architectural changes (swap serialization framework, change data flow) — the former zero-risk immediate gain, the latter needs regression testing. Experience ordering: first fix "wasted allocations" (logging, repeated compilation), then "redundant allocations" (intermediate trees, transit collections), finally consider "expensive but cheaper alternatives" (swap library, swap protocol). From wasted to redundant to expensive is the cost-effectiveness ladder of allocation governance.
1.7 Escape Analysis Failure Checklist
Common EA failure reasons collected into a checklist; when troubleshooting "why didn't it optimize," go through in order: ① Method not C2-compiled (not hot enough, TieredStopAtLevel=1 used); ② Loop body/large method not inlined , object deemed method-escaping (hot method too long); ③ Object passed to println , logging, reflection, etc. — non-inlinable boundaries ; ④ Object stored in collection or field (global escape, no optimization); ⑤ Deoptimized back to interpreter after compilation (optimization gains zeroed). This checklist connects directly to Article 08's tiered compilation and inlining mechanisms — EA gains are essentially "downstream dividends of inlining quality."
Read the failure list backwards and it becomes a "habit checklist to preserve EA": keep methods short (favors inlining), minimize reflection/dynamic proxies (fewer boundaries), keep object scope as local as possible (less global escape), keep loop bodies clean (favors loop optimization and inlining) — four habits not written for EA, but EA silently rewards them at every turn. This is the universal law of JVM tuning: optimization is JIT's "reward" for good structure, not "cash-in" for deliberate tricks; writing good code is itself the strongest JVM tuning — this series has now verified that sentence across three subsystems.
Production Practice: Allocation Profiling & Governance
2.1 Parameter Baseline for Allocation-Sensitive Services
A baseline for "allocation-sensitive, high GC frequency" online services — core idea: parameters only make measurement and optimization easier; they don't replace allocation governance itself. The baseline includes fixed heap ( -Xms4g -Xmx4g), G1GC, G1HeapRegionSize=2m for mid-small heaps to reduce humongous probability, unified GC logging with gc* level (includes allocation rate details), PrintFlagsFinal to archive actual EA-related switch values at startup. Notably, the config deliberately leaves a "placeholder trap": JDK has no AlwaysRecordAllocation parameter — the correct tool for allocation profiling is JFR, not a JVM switch. This line is written to remind: online "tuning parameter collections" contain many phantom parameters propagated by hearsay; verify any parameter with PrintFlagsFinal or jcmd VM.flags before landing. EA three switches stay default-on; only temporarily disable for controlled experiments.
This baseline also carries an "anti-tuning" manifesto: allocation-sensitive services have shorter parameter tables than general services — no Survivor surgery, no pause target micro-tuning, no generational thresholds, because those should be decided after allocation governance based on remaining problems. Parameter table length is a marker of governance maturity: the more mature the team, the fewer JVM parameters, the more code standards.
2.2 Allocation Profiling: JFR 10-Minute SOP
Standard action: a 10-minute JFR recording with allocation events, three commands:
jcmd <pid> JFR.start name=alloc settings=profile maxsize=250m duration=10m filename=/logs/alloc.jfr; apply typical load during recording;
jfr print --events AllocationAllocation --stack-depth 5 /logs/alloc.jfr | stats(or import into JMC Allocation view). Alternative: async-profiler allocation sampling ./profiler.sh -e alloc -d 60 -f alloc.html <pid> for 60-second flame graph.
Reading the profile has a fixed three-step caliber: Step 1: total trend (is allocation rate linearly correlated with traffic? non-linear suggests leaky cache or scheduled task amplification); Step 2: find top stacks (sort by bytes, top two governance gains usually exceed the rest combined); Step 3: attribute to code line (JFR stack depth 5 suffices to locate "our method"). Output is an "allocation governance checklist": each row "source stack → governance action → expected reduction", placed alongside Article 03's GC patrol checklist, reviewed biweekly.
Two engineering details make or break the SOP. First, recording window must cover real traffic shapes : recording only low peak misses "allocations that only appear at peak" (promo-specific branches, batch jobs) — record at least one high and one low peak. Second, profile must sort by "allocation bytes" not "allocation count" — a million 24-byte objects may have lower byte share than ten thousand 4KB intermediate trees, but GC only cares about bytes. These two biases can flip a profile's conclusion entirely; confirm caliber before reading.
2.3 Allocation Rate Observation: Dual-Caliber Logs
When JFR isn't convenient, GC logs can approximate allocation rate — take adjacent Minor GC timestamps and Eden usage:
grep "Pause Young" gc.log | adjacent time diff; awk accumulate Eden diff → hourly rate curve. Example: two GCs 8.2s apart, Eden consumed 1600M → rate ≈ 195 MB/s.
Each caliber has a blind spot: GC log caliber can't see "objects that died before reaching Minor GC" — they didn't cause GC but may waste CPU (object header, initialization); JFR caliber has sampling overhead, small object share underestimated. So rate from logs (precise), sources from JFR (comprehensive); don't mix the two calibers' numbers.
Concrete conversion for scale feel: a 5000 QPS service, 200 KB/request → ~1 GB/s total rate; 4 GB heap, 3.2 GB Eden → Minor GC ~every 3s. Reduce to 80 KB/request → 400 MB/s → frequency drops to 8s, single pause also drops because scan window shrinks. Same latency budget, allocation governance equals "free" 2.5× GC headroom — no added memory, no collector swap, no downtime. That's why mature teams put allocation profile in performance admission, while "tune GC parameters" goes after governance.
Upgrade rate observation to on-call caliber, two reference lines: allocation rate week-over-week up >30% with no traffic increase → check new code and scheduled tasks; rate-to-traffic ratio (bytes per request) rises → typical request got heavier or amplification logic deployed. Hook both into existing monitoring panels; GC-class fault detection moves from "frequency alert" one notch earlier to "numerator anomaly" — monitoring the numerator sees problems earlier than the denominator , this article's core increment to monitoring systems.
2.4 Governance Actions for Six Sources
Map Figure 5's six sources to actions: Log concatenation → lazy parameters (log.debug lambda overload), remove toString concatenation on hot paths; Regex → Pattern to static final or Caffeine cache, dynamic rules pre-compiled on change; Serialization → global ObjectMapper reuse (thread-safe), streaming to avoid intermediate trees; Stream transit → merge collect -then- stream chains, forEach instead of boxing; Boxing → hot loops swap to primitive arrays or Eclipse Collections; Exceptions → control flow to return values/ Optional, reuse no-stack-trace exceptions (static instances) when needed. Each is a single-line code change, yet GC curve gains are measured in multiples.
Governance acceptance criteria must be quantified: ① source share in allocation profile drops an order of magnitude; ② GC log caliber allocation rate measurably drops; ③ Minor GC frequency drops proportionally with rate (if not proportional, surviving objects increased — back to Article 03); ④ API P99 no regression (prevent "optimization" trading CPU for GC — e.g., cache reuse introducing lock contention). All four must pass; missing one means "cost shifting" not "cost elimination."
Finally distill governance actions into five code standards for team checklist: ① log parameters always lazy or guarded, hot paths forbid direct object concatenation; ② Pattern /compilation products always static final or cached, forbid method-internal compilation; ③ heavy objects like ObjectMapper always globally reused; ④ hot methods stay small and straight, no large new in loops, no calls to unknown boundaries; ⑤ exceptions not for control flow, high-frequency paths forbid throw. Five rules, each enforceable in a single code review line — the endgame of allocation governance isn't a few specialized optimizations, but standards that prevent problems from being born.
Standards land via "lint + review" dual insurance: static scan catches deterministic rules like Pattern.compile in method, loop-internal new ObjectMapper (Sonar custom rule half-day write); review catches semantic layer (does this object really need to exist? can scope be smaller?). Machine catches deterministic, human catches semantic — two lines of defense running three months, six sources naturally disappear from allocation leaderboard.
Core Source Code: Four Truths of Allocation
3.1 TLAB Fast Allocation
TLAB allocation core is "bump-the-pointer" — JIT-inlined form is shorter than source; here's the runtime equivalent logic:
// TLAB fast allocation (simplified collab logic)
HeapWord* tlab_allocate(size_t obj_size) {
HeapWord* top = tlab.top();
if (top + obj_size <= tlab.end()) {
tlab.set_top(top + obj_size);
// two instructions: bounds compare + pointer advance
return top; // initialize object header here
}
return nullptr; // slow path entry
}
// JIT inlined version more aggressive: caches end in register,
// fast path left with cmp + lea two machine instructions3.2 Escape Analysis Determination
C2's escape analysis tracks reference flow on the ideal graph — determination granularity is "per object, per edge" (simplified illustration):
// Escape state determination (simplified)
enum EscapeState {
NoEscape, // method-internal visible: scalar replaceable
ArgEscape, // passed/returned: may downgrade after inlining
GlobalEscape // field/thread visible: cannot optimize
};
// Key rules:
// - store to field/static/array -> GlobalEscape
// - as call argument -> ArgEscape
// (re-determine after callee inlined)
// - only local use, no above edges -> NoEscape3.3 Scalar Replacement Activation Conditions
NoEscapeobjects are merely "candidates"; actual replacement must pass several gates (simplified):
// Scalar replacement thresholds (MacroArrayCopy simplified)
bool can_eliminate(AllocationNode alloc) {
if (!alloc.is_non_escaping()) return false;
// Gate 1: must not escape
if (alloc.size() > MAX_ELIM_SIZE)
return false;
// Gate 2: object too large not worthwhile
if (alloc.is_locked()) return false;
// Gate 3: locked and lock not proven eliminable
if (alloc.has_unknown_field_access())
return false;
// Gate 4: uncertain field access exists
return true;
}
// After pass: fields split into SSA scalars, allocation node deleted3.4 Large Object Allocation Branch
Objects exceeding TLAB or humongous take slow path — G1's humongous determination at allocation entry diverts objects (cross-references Article 04 humongous section):
// G1 allocation entry branch (simplified)
HeapWord* mem_allocate(size_t size) {
if (size <= tlab.max_size()
&& Thread::current()->has_tlab()) {
HeapWord* p = tlab_allocate(size);
if (p != nullptr) return p;
}
if (size >= humongous_threshold()) {
// Humongous object: contiguous Region allocation,
// bypass TLAB, marked Humongous
return g1_alloc_humongous(size);
}
return eden_allocate_locked(size);
// Remaining slow paths: refill retry / lock Eden
}The four source sections connect into a complete "birth pipeline": entry tries TLAB (3.1), fails then diverts by size to humongous or lock Eden (3.4); whether JIT can "privately settle" an object off the pipeline depends on escape determination (3.2) and replacement gates (3.3). Understanding this pipeline gives code-level provenance to every number in jstat (Eden growth rate, TLAB waste, humongous count) — when reading logs you can mentally reconstruct the birth scene, and troubleshooting stops being guesswork.
Seven Accounts: Allocation Governance Cost-Benefit
Seven accounts together form a "project proposal": when requesting an allocation governance project from the team, use frequency and pause accounts to define benefits, habit account for long-term assets, risk account to draw boundaries (no promise of EA deterministic gains), observation account to constrain cost (JFR on-demand recording). Same structure as Article 05's migration seven accounts — all performance engineering decisions ultimately land on such "auditable ledgers," not feelings. This is the methodological dark thread running through Articles 03–06.
Final reminder: governance benefits have a ceiling — allocation rate can't go to zero, business objects must be born; when top sources are governed and rate enters normal range, marginal returns of further squeezing plummet; at that point shift energy back to GC parameters and capacity planning. Govern until "curve flattens" then stop; don't turn optimization into a mysticism contest — knowing when to stop is as professional as knowing where to start.
Frequency Account: Governing top 2 allocation sources typically cuts Minor GC frequency 30–70% (Incident 1: 73% source, one log line governed → minute-level) — benefit directly from formula numerator drop.
Pause Account: Rate down → single Minor GC scan surviving set shrinks synchronously → pause shortens. Only lever that simultaneously reduces frequency and single pause.
CPU Account: Less allocation = less header writes = less initialization = less GC scan, every link saves CPU; counterexample: optimization via cache reuse introducing lock contention, needs load test confirmation.
Memory Account: Less allocation → same pressure fits smaller heap — saved container memory is real money; conversely don't use "heap big enough" as excuse to skip allocation governance.
Risk Account: Optimizations relying on scalar replacement can vanish anytime due to inlining failure — any design treating EA as guarantee is a risk exposure; governance actions must land on deterministic patterns (reuse, lazy, pre-compile).
Observation Account: JFR overhead ~1–3%, production always-on needs trade-off; recommend "patrol recording 10 minutes" mode not always-on; GC log caliber for daily continuous observation.
Habit Account: Static Pattern, lazy logs, reuse Mapper — these patterns entering code standards cost near zero, benefits compound over service lifecycle; one code review普及, whole team benefits.
High-Frequency Interview Questions (with Answers)
20 Q&A covering allocation paths, TLAB, bump-the-pointer, escape analysis, scalar replacement, lock elision, inline relationship, GC frequency formula, observation calibers, six sources, log concatenation fix, Pattern.compile issue, ObjectMapper reuse, TLAB waste, large object bypass, scalar replacement verification, EA switches, heap increase vs CPU, governance acceptance criteria.
One-Page Cheat Sheet
Nine allocation sentences summarizing: ① four birth paths: scalar replacement > TLAB fast > slow > large object; ② TLAB pre-reserves, bump-pointer two instructions, lock-free search-free; ③ waste <5% designed cost, refill/resize auto-managed; ④ EA three tiers: non-escape replaceable, method-escape relies on inline downgrade, global-escape accepts fate; ⑤ stack allocation never implemented — scalar replacement is what works; ⑥ lock elision saves no-contention local locks, can't save shared state; ⑦ frequency formula: rate × survival ÷ Eden — numerator only root cure; ⑧ rate from GC logs, sources from JFR, dual calibers not mixed; ⑨ six sources: logs, regex, serialization, transit collections, boxing, exceptions — govern top 2 for multiplicative gains.
Summary & Next Article Preview
Reviewing three incidents: 2-second Minor GC query service — answer was govern that log line, not tune G1; DTO betting on scalar replacement — answer was write hot methods small and straight, not trust JIT; regex engine 18% allocation — answer was pre-compile cache. All allocation governance methodology compresses to one sentence: let objects that should die never be born, let objects that must be born be allocated blazingly fast — the former via coding discipline and escape analysis, the latter via TLAB, and JVM has already pushed the latter to the extreme; the rest is all in our code.
With allocation perspective filled, "object's life" has a complete closed loop: birth (this article TLAB & EA) → survival (Article 02 memory layout) → collection (Articles 03–05 three-gen collectors). Next article "Class Loading & Bytecode" leaves memory perspective, enters another subsystem: what class files look like, loading passes five gates, why parent delegation exists, and how bytecode becomes the raw material for all previous optimizations (inlining, EA, scalar replacement). If you can't read bytecode, you'll forever watch JIT through glass.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
