NOTE

7.16 Object Layout in Memory

Object composition, object headers, instance data, padding, and a JOL experiment.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Object Composition

There are two kinds of objects: ordinary objects and array objects.

1.1. Object Header

  1. Mark Word

Stores three kinds of information: the object’s hashCode, GC information, and lock information.

  • Lock information: the meaning of bits differs by state. The final three bits are related to locks: 001 represents the unlocked state, 00 represents a lightweight lock, 10 represents a heavyweight lock, and 101 represents a biased lock.

  1. Class pointer: points to the class. For example, if I call new Test(), this points to the address of Class<Test> in the method area.

  2. Array length: for an array, this value represents the length of the array.

1.2. Instance Data

For example, if Test has an Integer val field, its value is stored here.

1.3. Padding

Ensures 8-byte alignment; insufficient space is padded.

2. Experiment

  • pom.xml
<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.10</version>
</dependency>
  • ObjectTest
public class ObjectTest
{
    public static void main(String[] args)
    {
        Object object = new Object();
        String s = ClassLayout.parseInstance(object).toPrintable();
        System.out.println(s);
    }
}
  • Output

2.1. How Many Bytes Does an Object Occupy?

16 bytes.

3. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub