Week 9 - Object Layout, Headers, and Cache Effects¶
Conceptual Core¶
A Java object is not free. Every object has a header (mark word + class pointer), every reference is a pointer, and the layout interacts directly with CPU cache lines. "Compact" data structures in Java require understanding what HotSpot does to your fields.
Mechanical Detail¶
- Object header: mark word (8 bytes, holds lock state, identity hash, GC age, biased-locking bits in older JVMs) + klass pointer (typically 4 bytes with compressed oops). JEP 450 (Compact Object Headers), stable in 24+: reduces header to 8 bytes total. Material for any heap-sizing math.
- Field reordering: HotSpot reorders fields for alignment. Use JOL (Java Object Layout) -
java -jar jol-cli.jar internals com.foo.MyClass- to see the actual layout. - Compressed oops (
-XX:+UseCompressedOops, default ≤32GB heap). What happens above 32GB and how-XX:ObjectAlignmentInBytesextends the range. - Cache lines (typically 64 bytes). False sharing between adjacent fields written by different threads.
@Contended(JDK-internal injdk.internal.vm.annotation, requires-XX:-RestrictContended). - Primitive arrays are contiguous and dense; object arrays are arrays of pointers. Why
int[]is 4× smaller thanInteger[].
Lab¶
Use JOL to measure the size of: an empty object, a String, a HashMap with 0/1/10/100 entries, an ArrayList vs LinkedList of 1000 Integers. Predict each before measuring.
Idiomatic Drill¶
Read Aleksey Shipilëv's "Java Object Header" series.
Production Hardening Slice¶
Enable compact object headers (-XX:+UseCompactObjectHeaders if on 24+). Measure heap usage delta on a real app.