Video in progress
Why is creating an object with new so cheap in Java? What is a TLAB?
Each thread gets its own small buffer from eden, a TLAB (Thread-Local Allocation Buffer), and creates objects in it by just bumping a pointer. No lock and no search for free space is needed, so an allocation is a few instructions.
📖 Answer
In C, malloc searches for a suitable free block. In Java, eden is always "free space at the end", because a minor GC copies out the live objects and empties eden completely. So for a new object it is enough to move the top pointer forward by the needed number of bytes (bump-the-pointer).
So that threads don't get in each other's way, each one takes a chunk of eden:
eden: [ TLAB thread-1 | TLAB thread-2 | TLAB thread-3 | ... free ... ]
When a TLAB runs out, the thread asks for a new one, and only then is synchronization needed. If an object is too big for a TLAB, it is created directly in eden or (in G1) in a humongous region.
What this means in practice:
- don't be afraid of small short-lived objects: they are cheap to create and cheap to collect;
- but the allocation rate still matters: if you create gigabytes of objects per second, young GCs become very frequent;
- the JIT, through escape analysis, may not create some objects at all.
To see where most allocation happens, use the ObjectAllocationSample events in JFR or async-profiler's -e alloc mode.
Sign up to mark studied questions and save your progress.