In the Sun JVM, objects (other than arrays) have a head of two machine characters (words). The first word contains the marked hash code for this object and other identity information such as lock status and so on, and the second word contains a reference to the object's class. In addition, any object is 8 bytes aligned for granularity. This is the first rule of the object memory layout:
Rule 1: Any object is aligned with a granularity of 8 bytes.
For example, if you call new Object (), because the Object class does not have other members that can be stored, only 8 bytes in the heap are used to hold the two-word header.
Memory layout of classes that inherit object
In addition to the 8-byte head mentioned above, the class attribute is immediately followed. Attributes are usually arranged according to their size. For example, an integral type (int) is aligned in 4 bytes, and a long integer (length) is aligned in 8 bytes. This is designed for performance reasons: Typically, if the data is aligned in 4 bytes, it is more cost-effective to read 4 bytes of data from memory and write to the processor's 4-byte register.
To conserve memory, the Sun VM does not have a memory layout in the order of the attribute declaration. In fact, attributes are organized in memory in the following order:
1. Double type (doubles) and long Integer (longs)
2. Integral type (ints) and floating-point type (floats)
3. Short integer (shorts) and character type (chars)
4. Boolean (Booleans) and byte-type (bytes)
5. Reference type (References)
Memory usage is optimized through this mechanism. For example, declare a class as follows:
1 2 3 4 5 6 7 8 9 10 11 12-13 |
Class MyClass {byte A; int C; Boolean D; Long e; Object F; } |
If the JVM does not disrupt the declaration order of attributes, its object memory layout will look like this:
1 2 3 4 5 6 7 8 9 |
[Header:8 bytes] 8 [a:1 byte] 9 [padding:3 bytes] [c: |