Java object memory layout and java object Layout
Note: In this blog, refer to "deep understanding of Java Virtual Machine (version 2)"
1. The layout of objects stored in memory is divided into three parts:
- Object Header
- Data stored in the running hours of an object: Mark Word (the length of 32-bit and 64-bit virtual machines is 32-bit and 64-bit respectively), which contains the following information:
- Object hashCode
- Object GC generational age
- Lock status flag (lightweight lock, heavyweight lock)
- Lock held by the thread (lightweight lock, heavyweight lock)
- Bias locks: Some optimization strategies, such as biased locks, spin locks, lightweight locks, and others, are added to JDK1.6. These optimizations make the performance of Synchronized consistent with that of ReentrantLock, when Synchronized can meet the requirements, Synchronized is preferred unless some unique features of ReentrantLock are used, such as specified wait time.
- Type pointer: pointer to class metadata (32bit --> 32bit, 64bit --> 64bit (Compression Pointer not enabled), 32bit (Compression Pointer enabled ))
- Instance data: valid information for Real Object Storage
- Alignment Filling
- JVM requires that the object size be an integer multiple of 8. If not, the object must be bit-aligned.
2. Note
- Mark Word has a non-fixed data structure to store as much information as possible in a very small space.
- If an object is an array, the object header must have a set of data used to record the length of the array. JVM can determine the object length through the metadata of the Java object, but not for arrays.
- For Object Header Length
- The 32bit virtual machine must be 32bit + 32bit, that is, 8 bytes
- If the 64-bit VM has not enabled the compression pointer, It is 64bit + 64bit, that is, 16 bytes. If the compression pointer is enabled, it is 64bit + 32bit, that is, 12 bytes (not a multiple of 8 bits)
- -XX: + UseCompressedOops: Enable compression pointer
- In "deep understanding of Java Virtual Machine (version 2)", the object header is 8 bytes or 16 bytes. I don't know if it is incorrect. My system is not 64 bit and I have not tested it.
- Selection of basic data types and corresponding packages
In actual use, we will choose the basic data type or its packaging Class Based on the small number of bytes.
- In the second chapter JVM memory allocation, said, the actual memory size occupied by objects in the class load is completed after you can know, the specific is how to calculate, you can refer to this article http://www.importnew.com/14948.html