How Much Memory Does a Java Object Really Use? A JOL Walkthrough
This article explains how to calculate the exact memory footprint of a Java object using the OpenJDK JOL tool, covering object header composition, 8‑byte alignment, padding rules, and concrete examples for regular objects and char arrays.
To determine how many bytes a Java object occupies, you can use the OpenJDK JOL (Java Object Layout) tool.
Add the following dependency to your pom.xml:
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.10</version>
</dependency>Java objects are aligned to 8‑byte boundaries, so their total size is always a multiple of 8. An object consists of three parts: the object header, the instance data, and any padding needed to reach the alignment.
The object header includes a mark word (8 bytes) and a klass pointer (4 bytes). For array types, an additional field stores the array length.
For a simple object, after accounting for the sizes of its fields and the required padding, the total size in the example is 40 bytes .
For an array example:
char[] cs = new char[36];
System.out.println(ClassLayout.parseInstance(cs).toPrintable());The JOL output shows:
[C object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (1)
4 4 (object header) 00 00 00 00 (0)
8 4 (object header) 41 00 00 20 (536870977)
12 4 (object header) 24 00 00 00 (36)
16 72 char [C.<elements> N/A
Instance size: 88 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes totalSince each char occupies 2 bytes and the array length is 36, the calculated instance size is 88 bytes .
These calculations illustrate how JOL can be used to inspect object memory layout, understand padding, and verify the actual byte consumption of Java objects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.
