Article takes you understand how much memory you write Java objects actually accounted for?

Personal blog navigation page (click on the right link to open a personal blog): Daniel take you on technology stack 

Java memory model object header

Let's take a look at a Java memory model object is kind of how? Since our virtual machine is divided into 32-bit and 64-bit, it is certainly their model is different, I have listed below under the column of 32-bit and 64-bit virtual machine virtual machine Javaobject header memory model. # 32

# 64

64-bit pointer compression

Because the author of the local environment jdk1.8, 64-bit virtual machine, I'm here to 64 virtual machines (open pointer compression) to analyze, because by default, jdk1.8 the 64-bit virtual machine compression is enabled by default pointer.

Java object header consists of two parts, the first part is  Mark Word, this is the  Java lock realization of the principle in an important part of the other part  Klass Word.

Klass Word  here is actually a virtual machine designed oop-klass modelmodel, here OOPrefers to the Ordinary Object Pointer(common object pointer), looks like a pointer is actually hidden in the pointer in the object. And  klass it contains metadata and methods, to describe the  Java class. Open space under its occupation 32bits compression pointers in 64-bit virtual machine environment.

Mark Word  is the focus of our analysis, this knowledge will be designed to lock. Mark Word 64bits occupy space in 64-bit virtual machine environment. The entire Mark Wordallocation There are several situations:

  1. Unlocked (Normal):  hash code ( identity_hashcode) occupies 31bits, generational age ( age) occupies 4 bits, bias mode ( biased_lock) occupies 1 bits, a lock flag ( lock) occupies 2 bits, 26bits remaining unused (i.e., all 0)
  2. May be biased (Biased):  thread id accounted 54bits, epoch accounting for 2 bits, generational age ( age) occupies 4 bits, biased mode (biased_lock) occupies 1 bits, a lock flag (lock) occupies 2 bits, the remaining unused 1bit.
  3. Lightweight locking (the Lightweight Locked) : a pointer latch occupies 62bits, lock flag ( lock) occupies 2 bits.
  4. Heavyweight locks (Locked Heavyweight) : a pointer latch occupies 62bits, lock flag ( lock) occupies 2 bits.
  5. GC mark : flag accounted 2bits, the rest is empty (that is, filling 0)

These are our resolve to Java object header memory model, as long as Java object, then it will certainly include object header, which means that this part of the memory footprint is unavoidable. Under So, in my 64-bit virtual machine, Jdk1.8 (opened pointer compression) environment, any object, what not to do, as long as the declaration of a class, then its memory footprint on at least 96bits, which is at least 12 byte.

Verification Model

Let's look at some code to validate the above memory model, recommended here openjdk of jol tool , it can help you see the occupancy target memory.

First add maven dependent

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

Let's take a look, if only to create a common class, what attributes do not add, how much space is occupied?

/**
 * @description:
 * @author: luozhou
 * @create: 2020-02-26 10:00
 **/
public class NullObject {

}

According to our previous Java object memory model analysis, an empty object, it is only a subject's head, under the condition pointer compression will take up 96 bit, which is 12byte.

Run tool to view space occupied

 public static void main(String[] args) {
        System.out.println(ClassLayout.parseInstance(new NullObject()).toPrintable());
    }

The above line of code parses NullObject you create a new target, how much memory. We look at how the implementation of the results: Memory footprint

Here we find the results show: Instance size:16 bytesthe result is 16 bytes, our previous forecast of 12 bytes are not the same, why is this so? We see the figure above there are three rows object header, each occupying 4 bytes, so the head is 12 bytes, and this is consistent with our calculations, the last line is a virtual machine filled with 4 bytes, then why virtual confidential fill four bytes of it?

Memory Alignment

Want to know why the virtual machine is filled with 4 bytes, we need to understand what is memory alignment?

We look programmer memory is this:

The figure shows an embodiment a memory read pit radish. But in fact the CPU does not go with a one byte memory read and write. Instead the memory is a CPU reads a read block size and the like can be 2,4,6,8,16 byte size. We call this block size memory access granularity. As shown below:

Suppose a 32-bit platform's CPU, then it will go to a particle size of 4 bytes read memory block. Why we need to align memory? There are two main reasons:

  • Platform (portability) reasons: Not all hardware platforms are able to access any data on any address. For example: a specific hardware platform only allows to obtain specific types of data in a specific address, otherwise it will lead to an abnormal situation.
  • For performance reasons: If an unaligned memory access will result in twice the CPU memory access, and take additional clock cycles to process alignment and operation. And aligned itself requires only one memory access to complete the reading operation.

I used the legend to explain the process of the CPU to access non-aligned memory:

In the figure, assuming a CPU read is 4 bytes, 8 bytes in this continuous memory space, if my data is not aligned, the address stored in the memory blocks 1,2,3,4, and that reads the CPU will require two to read, plus additional computational operations:

  1. CPU first reads the first block of misaligned memory address, reads the byte 0-3. And remove the bytes 0.
  2. CPU reads the misaligned memory address of the second block again, 4-7 bytes read. 5,6,7 and remove the bytes byte.
  3. The combined 1-4 bytes of data.
  4. Merged into register.

Therefore, no memory alignment will cause additional CPU read operation, and requires additional calculation. If you do a memory alignment, CPU can start reading directly from the address 0, once the data you want to read, no additional read operations and arithmetic operations, saves the running time. We use the space for time, which is why we need to be aligned memory.

Back empty Java objects filled with four bytes of the problem, because the original byte header is 12 bytes, 64-bit machines, memory alignment word is 128, which is 16 bytes, so we also need to fill four words section.

Non-null object's memory footprint calculation

We know that an empty object is to occupy 16 bytes, a non-null object exactly how many bytes occupied it? We still write under a general category to verify:

public class TestNotNull {
    private NullObject nullObject=new NullObject();
    private int a;
}

This demo class introduced other objects, we know that intthe type is 4 bytes, NullObjectthe object occupies 16 bytes, object header accounts for 12 bytes, there is a very important case  NullObjectis a reference in the current class, so real object does not exist, but only keep the reference address , the reference address occupies 4 bytes, the total is 12 + 4 + 4 = 20 bytes, the memory alignment is 24 bytes. We are not under to verify this result:

public static void main(String[] args) {
        //打印实例的内存布局
        System.out.println(ClassLayout.parseInstance(new TestNotNull()).toPrintable());
        //打印对象的所有相关内存占用
        System.out.println(GraphLayout.parseInstance(new TestNotNull()).toPrintable());
        //打印对象的所有内存结果并统计
         System.out.println(GraphLayout.parseInstance(new TestNotNull()).toFootprint());
    }

The results are as follows:

We can see TestNotNullthe class space is 24 bytes, which occupies 12 byte header, the variable ais intthe type occupy 4 bytes, the variable nullObjectis referenced, takes up 4 bytes, and finally filled with four bytes, for a total of 24 bytes, consistent with our previous forecast. However, because we instantiate NullObjectthis object in memory for a while, so we need to add 16 bytes of memory footprint of this object, that is a total of 24bytes + 16bytes = 40bytes. The final results of our statistical print the figure is 40 bytes, so our analysis is correct.

This is also how to analyze how much memory the idea of ​​a real object is occupied, according to this line of thought plus openJDK of jol tool can basically write their own grasp of the "object" Prodigal you exactly how much memory.

to sum up

This article focuses on how to analyze me how much memory space is actually occupied by a Java object, the main points are summarized as follows:

  1. Java object model in memory head 32 virtual machines and 64-bit virtual machine is not the same, 64-bit virtual machine is divided into open and not open pointer pointer compression compression head model two kinds of objects, so a total of three kinds of objects head model .
  2. Memory alignment is mainly because of performance reasons and platforms, this paper is to resolve performance reasons.
  3. Empty object memory footprint calculation To calculate the memory alignment attention, memory, calculating a non-null object reference plus the attention space and footprint occupied by the original object instance.

Attached Java / C / C ++ / machine learning / Algorithms and Data Structures / front-end / Android / Python / programmer reading / single books books Daquan:

(Click on the right to open there in the dry personal blog): Technical dry Flowering
===== >> ① [Java Daniel take you on the road to advanced] << ====
===== >> ② [+ acm algorithm data structure Daniel take you on the road to advanced] << ===
===== >> ③ [database Daniel take you on the road to advanced] << == ===
===== >> ④ [Daniel Web front-end to take you on the road to advanced] << ====
===== >> ⑤ [machine learning python and Daniel take you entry to the Advanced Road] << ====
===== >> ⑥ [architect Daniel take you on the road to advanced] << =====
===== >> ⑦ [C ++ Daniel advanced to take you on the road] << ====
===== >> ⑧ [ios Daniel take you on the road to advanced] << ====
=====> > ⑨ [Web security Daniel take you on the road to advanced] << =====
===== >> ⑩ [Linux operating system and Daniel take you on the road to advanced] << = ====

There is no unearned fruits, hope you young friends, friends want to learn techniques, overcoming all obstacles in the way of the road determined to tie into technology, understand the book, and then knock on the code, understand the principle, and go practice, will It will bring you life, your job, your future a dream.

Published 47 original articles · won praise 0 · Views 268

Guess you like

Origin blog.csdn.net/weixin_41663412/article/details/104892981
Recommended