Sub topic 11
Allocation rate and GC pressure
This chapter assumes you can run Java from the command line, know what the heap is, and have read the earlier chapters on the JVM runtime model, GC logging, and Java Flight Recorder (JFR). Here you will learn how to measure how fast your program allocates objects, why that rate affects latency and throughput, and how to find the code responsible.
Why allocation matters
Creating an object on the JVM is cheap. In most collectors the JVM bumps a pointer inside a thread-local allocation buffer (TLAB), which costs a few instructions. The expense comes later. Every object that is created must eventually be reclaimed, and the garbage collector (GC) does that work.
The allocation rate is the number of bytes your application allocates per second, usually quoted in MB/s or GB/s. GC pressure is the load that this rate puts on the collector: how often it must run, how long it pauses your threads, and how much CPU it takes from your application.
A high allocation rate has these effects:
- The young generation fills quickly, so young collections happen more often.
- Objects have less time to die before a collection, so more of them survive and get copied. Copying costs time proportional to the live data, not the garbage.
- Survivors can be promoted to the old generation early. Old-generation collections are more expensive and, in some collectors, cause longer pauses.
- Allocation touches memory, which pollutes CPU caches even when GC is fast.
A program can have a low live set and still suffer if it allocates heavily. Allocation rate and heap occupancy are separate measurements.
The allocation path
Large arrays may skip the TLAB and be allocated directly in eden or, in G1, as humongous objects. Humongous objects are those at least half a G1 region in size. They are allocated in the old generation directly and are costly, so watch for them when you see large buffers.
Measuring the allocation rate from GC logs
You can estimate the rate without any profiler. Enable GC logging as in the earlier chapter:
java -Xlog:gc*:file=gc.log:time,uptime,level,tags -jar app.jarEach young collection line shows heap usage before and after, for example Pause Young (Normal) (G1 Evacuation Pause) 612M->38M(1024M). The next collection starts when eden fills again. To estimate the rate:
- Take the heap usage after one collection (38M).
- Take the heap usage before the next collection.
- Divide the difference by the elapsed time between the two collections.
If the heap goes from 38 MB to 612 MB in 2 seconds, the program allocates about 287 MB/s. You can also watch it live with jstat:
jstat -gcutil <pid> 1000The YGC column counts young collections and YGCT their cumulative time. If YGC rises several times per second, the allocation rate is high.
A program with a clear allocation problem
The Slow program from the tutorial concatenates strings in a loop. Each s += i creates a new string and copies all previous characters, so the work grows quadratically and allocates a great deal of garbage.
import java.util.ArrayList;
import java.util.List;
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Run it with GC logging and a small heap to make the effect visible:
javac Slow.java
java -Xmx256m -Xlog:gc:file=gc.log SlowYou will see many Pause Young entries in gc.log, each reclaiming almost everything. That pattern, frequent young collections with very little surviving, is the signature of short-lived garbage: high allocation rate, low retention. It is different from a leak, where the heap after each collection keeps growing.
Finding the allocating code with JFR
GC logs tell you that you allocate a lot, not where. JFR does. Record with the profile settings:
java -XX:StartFlightRecording=duration=60s,filename=app.jfr,settings=profile -jar app.jarJFR records allocations through two events:
jdk.ObjectAllocationInNewTLAB: an object allocation that caused a new TLAB to be requested.jdk.ObjectAllocationOutsideTLAB: an allocation that did not fit in a TLAB.
In JDK 16 and later, jdk.ObjectAllocationSample replaces these as the main event. It is a throttled sample, so its overhead is low, and it carries a weight field that estimates how many bytes the sampled event represents.
You can inspect the recording on the command line with the jfr tool, which ships with the JDK:
jfr summary app.jfr
jfr print --events jdk.ObjectAllocationSample --stack-depth 8 app.jfrFor aggregated results, open the file in JDK Mission Control and use the Memory page. It shows allocation by class and by stack trace. In the Slow example, the top classes would be java.lang.String and byte[], and the top stack frame would point to the main method line with s += i.
Keep these points in mind when reading allocation profiles:
- Allocation samples are statistical. Treat small differences as noise.
- The sampled stack shows where the allocation happened, which is not always the code you want to change. Walk up the stack to find the caller that decides how much to allocate.
- Sample weights matter. One large
byte[]can outweigh thousands of small objects, so sort by bytes, not by count.
Common sources of avoidable allocation
| Source | What happens | Typical fix |
|---|---|---|
| String concatenation in loops | A new string is built and copied each iteration | Use `StringBuilder` outside the loop |
| Boxing in collections | `List<Integer>` allocates an `Integer` for most values | Use primitive arrays or a primitive-specialized collection |
| Streams in hot paths | Lambdas, iterators and intermediate objects | Use a plain loop where profiling shows it matters |
| Repeated regex compilation | `Pattern.compile` called per request | Compile once and keep it in a `static final` field |
| Copying buffers | `Arrays.copyOf`, `String.getBytes` per call | Reuse buffers or work on slices |
| Logging with string building | Message built even if level is disabled | Use parameterized logging or a level guard |
| Unsized collections | `ArrayList` and `HashMap` resize and copy as they grow | Pass an initial capacity when the size is known |
Do not apply these blindly. Only change code that shows up in the allocation profile of your own application.
Escape analysis can hide allocation
The JIT compiler can use escape analysis to prove that an object never leaves a method. It can then avoid allocating the object on the heap at all (scalar replacement). This has two consequences. First, a short-lived helper object in a hot, compiled method may cost nothing, so removing it will not help. Second, a profile taken before the method was compiled may overstate allocation. Always profile a warmed-up application, and confirm any fix by re-measuring.
Reading the effect on the collector
After you change the code, compare the same metrics before and after:
- Allocation rate (MB/s) from GC logs or JFR.
- Young collection count and total pause time over the same workload.
- Application-level latency percentiles and throughput, since those are the goals you set at the start.
Lower allocation does not always mean faster code. If the change lowers allocation but raises CPU time elsewhere, the net effect can be negative. Judge success by the end-to-end goal.
Tuning versus fixing
You can also respond to GC pressure by tuning: a larger young generation (-Xmn, or a larger -Xmx so the collector sizes it larger) means fewer, though longer, young collections when most objects die young. Tuning treats the symptom. Reducing allocation in the hot path treats the cause, and it usually helps every collector. Try tuning as a quick check of how sensitive the program is, then fix the code.
Exercises
Exercise
GC logs show young collections about every 500 ms. Heap after each collection is 40 MB, and heap before the next collection is 440 MB. What is the approximate allocation rate, and does the pattern suggest a leak?
Show answer
The program allocates about 400 MB in 0.5 s, so roughly 800 MB/s. A flat 40 MB after each collection means the live set is not growing, so this is short-lived garbage and not a leak. The next step is to record JFR allocation events and find the stack traces that allocate the most bytes.
Exercise
After replacing a short-lived helper object with a reused one, your benchmark shows no improvement. Give one likely reason related to the JIT compiler.
Show answer
Escape analysis probably already eliminated the allocation in the compiled hot method through scalar replacement, so the original object never reached the heap and there was nothing to save. The profile or reasoning that suggested the allocation was likely taken from interpreted or early-tier code.