Monday, December 22, 2025

Java 25: Compact Object Headers

Java 25 introduces Compact Object Headers, an optimisation that reduces the memory overhead of Java objects.

In my previous post, I wrote about how you can measure the size of java objects using JOL, and inspect the size of the object header. For example, take the following class:

public class Point {
  int x;
  int y;
}

Use JOL to inspect its layout:

import org.openjdk.jol.info.ClassLayout;

public class JolExample {
  public static void main(String[] args) {
    System.out.println(ClassLayout.parseClass(Point.class).toPrintable());
  }
}

The output is:

Point object internals:
OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     N/A
  8   4        (object header: class)    N/A
 12   4    int Point.x                   N/A
 16   4    int Point.y                   N/A
 20   4        (object alignment gap)    
Instance size: 24 bytes

This shows that even though the Point class only has 2 int fields requiring a total of 8 bytes, the actual object uses three times that amount (24 bytes), due to the object header (12 bytes) and alignment (4 bytes).

Now let's turn on Compact Object Headers using the following JVM flag:

-XX:+UseCompactObjectHeaders

Rerunning JOL, outputs the following:

Point object internals:
OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     N/A
  8   4    int Point.x                   N/A
 12   4    int Point.y                   N/A
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

As shown above, with compact object headers enabled, the object header now takes 8 bytes instead of 12, a saving of 4 bytes.

Previously, the object header layout was split into a mark word (8 bytes) and a class word (4 bytes). With compact object headers, the division between the mark and class words is removed, and the class word is subsumed into the mark word for a total of 8 bytes.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.