Understanding Java Object Memory Allocation and Thread‑Local Allocation Buffers (TLAB)
This article explains how the JVM allocates memory for Java objects, discusses the thread‑safety challenges of concurrent allocations, and describes the Thread‑Local Allocation Buffer (TLAB) mechanism and its impact on performance and garbage collection.
JVM memory structure is a crucial topic for developers preparing for interviews, covering heap, stack, and method area.
The article introduces how Java objects are allocated in the heap, noting that object creation can use various methods such as new , reflection, or cloning, but ultimately requires memory allocation.
When the new instruction is executed, the JVM first checks whether the class is loaded, then determines the required space based on instance variables and reserves a region in the Java heap (assuming no JIT optimizations).
Different garbage‑collector algorithms affect how the heap is fragmented; for example, the mark‑sweep algorithm can leave non‑contiguous free spaces that must be managed via free‑lists.
In concurrent scenarios, thread‑safety of memory allocation is a concern: if two threads point to the same memory region, inconsistencies can arise.
Two solutions are presented: (1) synchronize the allocation step, often using CAS with retry logic, and (2) pre‑allocate a small private memory block per thread, known as Thread‑Local Allocation Buffer (TLAB).
TLAB is used by the HotSpot JVM: each thread gets its own buffer from the heap for fast allocation, while reading, usage, and garbage collection remain shared among threads.
TLAB operates only in the young generation’s Eden space; large objects that don’t fit are allocated directly in the old generation, so creating many small objects is generally more efficient.
The JVM’s use of TLAB can be toggled with the -XX:+UseTLAB or -XX:-UseTLAB flags.
In summary, TLAB provides thread‑exclusive allocation to improve safety and performance, while keeping other operations thread‑shared, and can be enabled or disabled via JVM options.
References: "深入理解Java虚拟机" and online articles such as https://www.cnblogs.com/straybirds/p/8529924.html and related Zhihu discussion.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.