An int type of 4 accounts for 4 bytes of memory, one byte in bytes. But is their package type Integer,byte object memory loss still the same? Not, and the gap is huge.
In a hotspot virtual machine, a common Java object is composed of 3 parts
- Object Header
- instance data defined within a class
- Memory alignment
2 Needless to say, the Java object does not have the definition good instance word Gencun what.
The object header is also divided into two parts, Mark Word and the type pointer. Mark Word stores object run-time data, such as the object's hashcode, the age of the object, the lock state, and so on. The generational age of an object is entirely designed for the JVM's young GC, and the generational age of the object is added one after each young GC's surviving new generation of objects. Until this field grows to a threshold, the object is promoted to the older generation (tenured generation). This field gives 4 bits, which means that a Java object undergoes a maximum of 16 times for the young GC and is not recycled, so it will enter the old age. The hashcode accounted for 25bit, the lock marker was 2bit, and a bit was fixed at 0. That is, the entire mark Word accounts for 4 bytes.
Each instance of an object corresponds to a class object in the method area. The type pointer of the object header is the metadata of the class that is used to locate it. Why do I have to save this data? One reason is that the method area also has a GC (exactly full GC), and if there is no class instance pointing to the class object of the method area, then the class object will be unloaded for recycling. I wonder if you have ever experienced a mistake like java.lang.OutOfMemoryError:PermGen space. If the class is always loaded, the permanent generation is bound to explode. 32-bit JDK, class-type pointers account for 4 bytes.
Now talk about memory alignment. Memory alignment is not a patent for the JVM, and C/C + +, class objects are also memory-aligned. The hotspot requires that an object's start and end address must be a multiple of 8, because the object header is exactly 8 bytes, so when the class field is misaligned, it needs to be aligned by padding. Why do we have to align? Data is not accounted for less memory, the better? This is the time to mention our CPU cache (L1 cache, L2 cache), which are all 64-byte rows.
To answer the question at the beginning, the integer size is 4 times times the int (with an extra 4Byte complement), and byte is 16 times times the byte (with an extra 7Byte complement). Did you figure it out?
Looking at "effective Java" two years ago, there is a section that mentions using as much as 8 native types, at which point there is no concept of Java Object Memory layout at all. Now in retrospect, this suggesstion is very constructive. Can save a lot of memory, especially when reading a lot of fields from DB.
In-depth understanding of Java Virtual Machines reading notes: Memory layout of objects