All notes

· Per Lilja

Unveiling Java Object Headers: the key to memory efficiency

What lives in the mark word and class word of every Java object, and why it matters for locking, garbage collection and Project Lilliput.

In a previous post, I wrote about an exciting upcoming feature in Java called Project Lilliput, or JEP 450. However, when I heard about this feature and how much memory it could save, I realized I knew nothing about Java object headers.

As Java developers, we often focus on high-level constructs like classes, methods and interfaces. However, the internal workings of the Java Virtual Machine (JVM) responsible for memory management often go unnoticed. Object headers are crucial to the JVM’s internal operations and the garbage collector’s performance.

So, I went down the rabbit hole to learn more about Java object headers.

What are object headers?

Every Java object in the JVM has a metadata block associated with it called the object header. These headers are essential for the JVM’s internal operations and the garbage collector (GC) to perform their respective tasks efficiently.

The object header is divided into the mark word and the class word.

Mark word

The mark word is a crucial element of the Java object header and comes before the class word. It’s a field with a versatile structure that changes its content based on the object’s state.

On a 64-bit JVM, the first 2 bits are the tag, then come 4 bits with GC age information and a hash code consisting of 31 bits. The rest is unused.

However, in some cases, the mark word consists of a pointer to a data structure, and then all the bits are used except the first 2, which are still used for the tag.

The exact layout of the mark word, including the tag, can be complex and varies depending on factors such as the object’s state and whether the JVM runs in 32-bit or 64-bit mode. Understanding this layout can be useful for low-level JVM tuning and optimization.

Tag

The tag in the mark word of a Java object header is typically used as a marker to indicate an object’s current status or state in the JVM. However, the exact use of the tag can vary depending on the implementation of the JVM, as it’s not specified in the Java Language Specification.

In Oracle’s HotSpot JVM, the mark word can be in one of several states, including unlocked, locked, marked and biased. The tag, represented by a few bits in the mark word, indicates which of these states the object is currently in.

Here’s a general breakdown of these states:

  1. Unlocked (default) state: the mark word contains thread-agnostic information, such as the object’s hash code (if it has been computed) and the object’s age (how many garbage collection cycles it has survived).
  2. Locked state: when an object is locked for synchronization (e.g., when it’s being used in a synchronized block), the mark word contains a pointer to a lock record (also known as a “displaced header”) on the executing thread’s stack.
  3. Marked state: during a garbage collection cycle, the garbage collector may temporarily repurpose the mark word as a marking flag to keep track of whether an object is reachable.
  4. Biased state: to optimize synchronization operations, HotSpot JVMs can use a technique called biased locking. In this state, the mark word contains the identifier of the thread that owns the object’s lock bias.

GC age

In the context of Java object headers, the GC age, or age bits, represents how many garbage collection cycles the object has survived without being reclaimed. This is an essential component of the generational garbage collectors used in most modern JVM implementations.

Generational garbage collectors operate on the assumption that “most objects die young”, meaning that objects are more likely to become unreachable (and therefore eligible for garbage collection) shortly after they are created. This observation is often referred to as the weak generational hypothesis.

To take advantage of this hypothesis, the JVM’s heap memory is divided into two primary regions: the young and the old generation. New objects are allocated in the young generation, and if they survive multiple GC cycles, they’re promoted (moved) to the old generation.

The GC age field in the object header keeps track of how many GC cycles an object in the young generation has survived. Once this number reaches a certain threshold, the object is considered old and promoted to the old generation. The specific threshold can be configured with JVM options.

Therefore, the GC age in the object header is crucial to the JVM’s memory management and garbage collection process. It helps the JVM optimize memory usage by allocating objects in different heap regions based on their expected lifetimes.

Hash code

The hash code part of the mark word is used to store the object’s identity hash code. This becomes particularly relevant when the hashCode() method is invoked on an object.

In Java, every object inherits a hashCode() method from java.lang.Object. This method returns an integer intended to be a somewhat unique identifier for the object. This hash code is used extensively when objects are inserted into hash-based collections like HashMap and HashSet.

When hashCode() is called for the first time on an object, the JVM computes the hash code and stores it in the mark word of the object header. The specifics of how this hash code is computed can vary between JVM implementations.

After the hash code is generated and stored, subsequent calls to hashCode() return the stored value instead of recomputing it. This is crucial for performance, especially for complex objects where computing the hash code might be expensive.

However, if the object’s mark word is being used for other purposes (like locking), the JVM may have to store the hash code elsewhere, like in a separate data structure associated with the object.

It’s important to note that although every object has a hashCode() method, it’s not always used or relevant. For instance, if an object isn’t used as a key in a hash-based collection and its hashCode() method isn’t explicitly called, the JVM might never compute or store its hash code.

Class word

The class word, also known as the class metadata pointer, is the other critical component of the object header. It contains a pointer to the metadata of the object’s class.

This metadata is vital for the JVM to understand the object’s layout in memory, including the type and order of its fields, and to access the methods that belong to the object’s class. The metadata includes:

  1. The fully qualified class name: the name of the class, including its package.
  2. Class modifiers: whether the class is public, abstract, final, etc.
  3. Field information: the class’s fields, including their names, types and modifiers.
  4. Method information: all the methods defined in the class, including their names, return types, parameter types and the bytecode of their implementations.
  5. Constant pool: all the constants (literal values and references to other classes and methods) that the class uses.

Together, the mark word and the class word hold crucial metadata about a Java object, allowing the JVM to manage memory effectively, enforce access control rules, and perform operations like garbage collection and synchronization.

Conclusion

Understanding object headers and their role in Java memory management is crucial for every developer seeking to write performance-optimized code. With initiatives like Project Lilliput, the future of Java looks promising, with the potential for more memory-efficient applications that can handle larger workloads. As developers, staying aware of these advancements and understanding their implications will empower us to leverage the full potential of the Java platform.

Remember, optimizing memory usage in Java is not just about writing leaner code; it’s also about understanding the intricacies of the JVM and how it handles objects under the hood. Keep exploring, and happy coding!

Further reading

Have a hard problem? Let’s talk.

A 30-minute intro call, no pitch deck. You describe the problem, I tell you honestly whether I’m the right person for it.