Object Allocation
TL;DR
- Creating objects in Java is relatively cheap, but Garbage Collecting them is expensive.
- High object allocation rates in tight loops trigger frequent Minor GC pauses, destroying application throughput.
- You can optimize allocation by reusing objects, using primitive types instead of wrappers, and using correct initial capacities for collections.
Concept
Every time you use the new keyword, the JVM allocates memory on the Heap. The JVM Heap is divided into regions, primarily the Young Generation (where new objects go).
If a web application creates 10,000 temporary objects per HTTP request, and it receives 1,000 requests a second, it is allocating 10,000,000 objects per second. The Young Generation will fill up in milliseconds. The JVM must then pause your application threads, scan for dead objects, and clear the memory. This is called a Minor GC pause. High allocation rates lead to constant GC pauses, causing latency spikes and CPU churn.
Examples
public class AllocationDemo {
// ❌ BAD: High Allocation Rate
public int sumListSlow(List<String> numbers) {
int sum = 0;
for (String numStr : numbers) {
// Integer.valueOf() creates a NEW Integer object on the heap!
// It is immediately unboxed and discarded.
Integer obj = Integer.valueOf(numStr);
sum += obj;
}
return sum;
}
// ✅ GOOD: Zero Object Allocation
public int sumListFast(List<String> numbers) {
int sum = 0;
for (String numStr : numbers) {
// Integer.parseInt() returns a raw primitive 'int'.
// No objects are created on the heap, saving massive GC overhead.
sum += Integer.parseInt(numStr);
}
return sum;
}
}
Interview Questions
Q: Why should you specify the initial capacity of an ArrayList or HashMap?
A: If you write List<String> list = new ArrayList<>(), Java creates a backing array of size 10. If you then add 10,000 items to it, the array fills up. Java must allocate a new array of size 15, copy everything over, and discard the old array. It will do this roughly 13 times, creating and discarding 13 increasingly large arrays, generating garbage.
If you write new ArrayList<>(10000), exactly one array is allocated, preventing all intermediate garbage creation.
Q: What is “Escape Analysis” in the JVM?
A: Escape Analysis is an advanced JIT compiler optimization. If you create a temporary object inside a method (like Point p = new Point(1, 2);), and the JVM proves that the object never “escapes” the method (it isn’t returned, nor passed to another thread), the JVM will not allocate the object on the Heap! Instead, it allocates the object’s primitive fields directly on the Thread Stack. When the method ends, the memory is instantly reclaimed without involving the Garbage Collector.