Video in progress
How do you find and reduce excess allocation caused by collections on a hot path?
First I use an allocation profile (async-profiler -e alloc or JFR) to see which place allocates the most bytes. The usual culprits in collections are boxing, repeated copies, resizes and short stream chains. I cut them down by giving initial sizes, copying once, and using primitive structures.
📖 Answer
The signs: in the GC log, young-generation collections several times a second, a noticeable share of CPU in GC threads, and p99 latency spiking together with GC pauses. If the allocation rate goes above a gigabyte or two per second, somewhere something is usually creating needless objects.
Measuring:
# a 60-second allocation profile, flame graph
asprof -e alloc -d 60 -f alloc.html <pid>
# or JFR
jcmd <pid> JFR.start duration=60s settings=profile filename=app.jfr
In JFR I group the jdk.ObjectAllocationSample events by stack.
Frequent culprits:
- Boxing. A
Map<Long, Integer>counter, measurements in aList<Double>.Long.valueOfcreates a new object every time outside -128..127. The fix is a primitive array or a primitive map, andLongAdderfor counters. - A copy on every call:
new ArrayList<>(items)in a getter,List.copyOf,toArray(). If the internal state is immutable, take the copy once in the constructor. - Resizes. A list or map built on every request grows 10 → 15 → 22. Give the expected size:
new ArrayList<>(n),HashMap.newHashMap(n). - Stream chains on small collections: lambdas, a
Spliterator, intermediate objects. Where it is called hundreds of thousands of times per second, a plain loop is often cheaper. But the JIT's escape analysis eliminates some iterators and small objects entirely, so I decide from the profile, not from guesses. - Lookup Maps rebuilt on every request: build them once and keep them.
After the fix, in JMH I compare gc.alloc.rate.norm (bytes per operation) with -prof gc before and after. "It seems faster" isn't enough, I need a number. And I apply the harder-to-read optimizations only where the profile shows them at the top.
Sign up to mark studied questions and save your progress.