[Java] How to view the memory layout of an object in Java

Insert picture description here

1 Overview

Some blogs say that the memory layout of Java is divided into 3 parts, so how do we confirm this? Or how to print the memory layout of java objects?

The following describes the use of this class

First introduce this package

        <dependency>
            <groupId>org.openjdk.jol</groupId>
            <artifactId>jol-core</artifactId>
            <version>0.10</version>
        </dependency>

Then, create a class

public class L {
    
    
    private boolean flag = false;
}

Then the test class is as follows

    @Test
    public void printAble(){
    
    
        L l = new L();
        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    }

Can be seen as follows

com.java.lock.obj.head.L object internals:
 OFFSET  SIZE      TYPE DESCRIPTION                               VALUE
      0     4           (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4           (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4           (object header)                           a3 1c 01 f8 (10100011 00011100 00000001 11111000) (-134144861)
     12     1   boolean L.flag                                    false
     13     3           (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 3 bytes external = 3 bytes total

Analyzing here, you can see that 3 object headereach occupy 4 bytes, and then the boolean occupies one byte. These total 3*4+1=13 bytes, because java requires objects

  1. At least 8 bytes
  2. Object must be an integer multiple of 8

Therefore the last 3 bytes are object aligned.

Let's verify that we create a class, but it is of type Int.

public class L {
    
    
    private int flag ;
}

Then run the test class and print as follows

 @Test
    public void printAble(){
    
    
        L l = new L();
        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    }

Can be seen as follows

 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           a3 1c 01 f8 (10100011 00011100 00000001 11111000) (-134144861)
     12     4    int In.flag                                   0
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

Exactly int occupies 4 bytes, and the result is exactly 16 bytes, a multiple of 8, so there is no object filling operation.

Guess you like

Origin blog.csdn.net/qq_21383435/article/details/110727931