Like attention, no more lost, your support means a lot to me!

🔥 Hi, I’m Chouchou. GitHub · Android-Notebook has been included in this article. Welcome to grow up with Chouchou Peng. (Contact information at GitHub)

preface

  • Java objects are a lot of contact, the correct understanding of Java object memory layout & access, is also the basis of Java programming;
  • How many bytes will I take with Object obj = new Object() in this article? This question is a clue to explore the memory layout & access of objects on the Java heap. Please be sure to like and follow if you can help, it really means a lot to me.

directory


1. Experimental results

JOL (Java Object Layout) is a tool provided by the OpenJDK to analyze the memory Layout of objects. The main limitation is that it only supports HotSpot/OpenJDK VMS. If used on other VMS, an error will be reported:

java.lang.IllegalStateException: Only HotSpot/OpenJDK VMs are supported
Copy the code

Now we use JOL to analyze the memory layout of the new Object() on the HotSpot virtual machine:

Implementation 'org.openjdk.jol: jo-core :0.11' Step 3: Print the object memory layout. 1. Print the information about the object memory layout of the VM. 2. Output object memory layout information System. Out. The println (ClassLayout. ParseInstance (obj). ToPrintable ());Copy the code

The following output is displayed:

# Running 64-bit HotSpot VM. # Using compressed oop with 3-bit shift. # Using compressed klass with 3-bit shift. # Objects are 8 bytes aligned. # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] java.lang.Object 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) e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243) 12 4 (loss due to the next object alignment) Instance size: 16 bytes Space losses: 0 bytes internal + 4 bytes external = 4 bytes totalCopy the code

Vm information:

  • Running 64-bit HotSpot VM.Represents a HotSpot VIRTUAL machine running on 64-bit
  • Using compressed oop with 3-bit shift. See section 7 for analysis
  • Using compressed klass with 3-bit shift.See section 7 for analysis
  • Objects are 8 bytes aligned.Indicates that the object is aligned by 8 bytes
  • Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes], in turnReference, Boolean, byte, char, short, int, float, long, doubleType length, see source code:
HotspotUnsafe.java

public String details() {
    // ...
    out.printf("# %-19s: %d, %d, %d, %d, %d, %d, %d, %d, %d [bytes]%n",
                "Field sizes by type",
                oopSize,
                sizes.booleanSize,
                sizes.byteSize,
                sizes.charSize,
                sizes.shortSize,
                sizes.intSize,
                sizes.floatSize,
                sizes.longSize,
                sizes.doubleSize
        );
}
Copy the code
  • Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]Represents, in turn, the array element length

In the information about the Object Object, although there are many unknown data, at least you can clearly see the Instance size: 16 bytes. Is that the answer to the question?


2. Basic structure of object memory layout


3. Object headers

The object header contains the Mark Work and an optional type pointer & array length. Since the information in the object header is an additional storage cost unrelated to the object instance data, Mark Word is designed as a stateful dynamic data structure that reuses its own storage space based on the object’s state.

3.1 Mark the Work

3.2 Class Pointer

  • Definition: Points to type metadata in the method area
  • Length: 4 bytes on 32-bit machines and 8 bytes on 64-bit machines. The virtual machine (default) compresses the length to 4 bytes through pointer compression, controlled by the following virtual machine parameters, as described in Section 7 of pointer compression
-XX:+UseCompressedClassPointers -XX:+UseCompressedOops
Copy the code
  • Note: Not all virtual machine implementations store type Pointers on object data. Depending on how objects are accessed by the VIRTUAL machine, if direct Pointers are used, the memory layout of the object must place Pointers to access type data.

3.3 (Optional) Array Length

  • Definition: The length of the index group object (refers to the number of elements, but does not occupy memory space).
  • Length: 4 bytes
  • Description:ordinaryJavaThe size of an object can be determined from metadata information, but the length of an array object cannot be determined from metadata information. So if the object is aJavaArray, then there will be an area in the object header that records the length of the array. Such as:
Char [] STR = new char[2]; System.out.println(ClassLayout.parseInstance(str).toPrintable()); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- JOL: [C 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) 41 00 00 f8 (01000001 00000000 00000000 11111000) (-134217663) 12 4 (Object header) 2】02 00000000 (00000010 00000000 00000000 00000000) (2) 16 4 char [C.<elements> N/A 20 4 (Loss due to the next object alignment) Instance size: 24 bytes Space losses: 0 bytes internal + 4 bytes external = 4 bytes totalCopy the code

You can see that there is a 4-byte area in the object header with a value of 2, indicating that the array is 2 in length.


4. Instance Data

Instance data is the valid information of an object, which can be interpreted as payload in a packet segment. The instance data of an object includes instance fields declared by the class and instance fields inherited from its parent, but not class-level fields (stored in the method area). The order in which fields are stored depends on the order in which fields are declared and the allocation policy parameters:

  • Fields of the same width are allocated together: Longs/Doubles, INts, shorts/chars, Bytes/Booleans, Oops (Ordinary Object Pointers, Oops)

  • Superclass fields precede subclass fields

  • Use -xx: FieldsAllocationStyle, +XX: CompactFields to influence the allocation strategy


5. Align Padding

HotSpot requires that object sizes be 8 bytes aligned (Objects are 8 bytes aligned in the first section). If the object takes up space that is not a multiple of 8 bytes, you need to add alignment padding data.

Intuitively, “invalid” padding data makes objects occupy more space and increases the memory consumption of virtual machines. So why do it? ** The main reason is that neat object alignment is a prerequisite for pointer compression, ** see section 7.


6. Access and locate objects

As we all know, Java types can be divided into basic data types and Reference types, and Reference types are needed to access objects. The mainstream access methods are divided into handle access & direct pointer access:

  • Handle access:

Definition: Reference stores the address of an object’s handle in a separate pool of handles in the Java heap. The handle stores the address of the object instance data and the type data.

Advantages: The address of the object instance data and type data in the handle is stable. When the object is moved during garbage collection, only the pointer of the instance data needs to be modified, but the Reference itself does not need to be modified.

  • Direct pointer access:

A Reference contains a block of memory containing the instance data and a Pointer to the type data. This Pointer is the Class Pointer we saw in Section 3 (2).

Advantages: Faster access because a pointer access is saved.

7. Pointer compression

Editting…


The resources

  • JVM Anatomy Quark #23: Compressed References — By Aleksey ShipilÑ‘v
  • In Depth understanding the Java Virtual Machine (version 3) (chapters 2 and 13). By Zhou Zhiming
  • Advanced Android Decryption (Chapter 10). By Liu Wangshu
  • The Art of Concurrent Programming in Java (chapters 2 and 6). By Fang Tengfei, Wei Peng, and Cheng Xiaoming

Recommended reading

  • Java | show you understand the ServiceLoader principle and design idea
  • Java | please outline the structure of a Class file
  • Java chat | compilation process (compile front-end & compile the back-end)
  • Java | why Java implementation platform neutrality?
  • How many letters are there in the Android | a process Context object is not much (right)
  • Android | show you understand NativeAllocationRegistry principle and design idea
  • Android | article bring you a comprehensive understanding of AspectJ framework
  • Computer composition principle | Unicode utf-8 and what is the relationship?
  • | why floating-point arithmetic of computer constitute principle is not accurate? (Ali written test)

Thank you! Your “like” is the biggest encouragement for me! Welcome to attentionPeng XuruiThe lot!