How do I view the memory layout of an object
  • Java Object Layout (JOL)
  • Address mvnrepository.com/artifact/or…
Jol printed out the details of the information

The following two lines of code print information about an Object in memory

Object obj = new Object();
System.out.println(ClassLayout.parseInstance(obj).toPrintable());
Copy the code

The output is shown below:

It can be divided into three parts

  • Object head
    1. Mark Word: The first red box stores the object’s HashCode, GC generation age (4 bytes, maximum 1111 in binary, 15 in decimal), lock status flag, the lock held by the thread, bias thread ID, bias timestamp
    2. Class Pointer: The second red box that points to a Class object (4 bytes on 32-bit systems, 8 bytes on 64-bit systems, 4 bytes on 64-bit systems after Pointer compression is enabled, Pointer compression is enabled by default)
  • Instance data: This is not printed because there are no other properties in Object
  • Padding: Third red box that makes the object size an integer multiple of 8

So the size is the object header + instance data + alignment, i.e. (8+4) +0+4=16 bytes

Custom class information in memory details
// Define a class
public static class TestObject{
        int a;
        int b = 1;
        TestObject o;
}
Copy the code
/ / print TestObject
TestObject objTest = new TestObject();
System.out.println(ClassLayout.parseInstance(objTest).toPrintable());
Copy the code

The output is shown below.

You can see that there is an object instance here, but since it happens that 24 bytes are multiples of 8, it is not aligned.