What does the instantiation of an object do? First Java is an object-oriented language, belongs to the category of all objects of the class is abstract, all structured information of object defined in the class, so the object creation needs according to define the type of information in class, which is kind of corresponding class of binary byte stream, so this goes to class loading and initialized. Second, objects are mostly stored in heap memory, which involves memory allocation. In addition, there are variables of the initialization of zero value, the setting of the object header, in the stack to create a reference to the object, and so on, this article we come together with a detailed analysis of the complete instantiation of the object process.

1 Overall process

The entire instantiation process is shown in the following figure:

To get the story moving, let’s define a Demo that will discuss in detail how dc objects are created and instantiated.

public class Demo
{

    public static void main(String[] args)
    {
        DemoClass dc=newDemoClass(); }}class DemoClass
{
    private static final int a=1;
    private static int b=2;
    private static int c;
    private int d=4;
    private int e;
    static
    {
        c=3;
    }
    public DemoClass(a)
    {
        e=5; }}Copy the code

Type 2 initialization check

Here we use the new keyword to create objects. There are many ways to create objects in Java, such as reflection, cloning, serialization and deserialization, and so on. These methods vary, but when compiled by the compiler, the corresponding instruction in the Java virtual machine is actually a new instruction (the new instruction is different from the new keyword mentioned earlier, this is the virtual machine level instruction). When the Java virtual machine run into a new instruction, will first according to the instruction to the corresponding parameters in the constant pool to find whether there is a symbol of the corresponding references, and determine whether the class has been loaded, parsed, initialization, namely to method check for the type of the class information in the area, if not, the first class loading and initialized. If the class is already loaded and initialized, proceed.

This assumes that DemoClass has not been loaded and initialized, that is, there is no DemoClass type information in the method area. In this case, DemoClass needs to be loaded and initialized.

Class 3 loading process

The class loading process can be divided into seven steps: load, verify, prepare, parse, initialize, use, and unload. Here we look at the first six stages.

loading

The loading phase does three things:

  1. Gets the binary byte stream of a class based on its fully qualified name.

  2. Transform the static storage structure represented by the binary byte stream into a runtime data structure in the method area.

  3. Create a java.lang. Class object in memory that represents this Class and acts as an access point to the various data of this Class in the method area.

The demoClass. class binary file is located according to the package.DemoClass fully qualified name, and the. Class file is loaded into memory for parsing, and the parsed result is stored in the method area. Finally, a java.lang. Class object is created in the heap memory to access the Class information loaded in the method area.

validation

The main task of the validation phase is to ensure that the information contained in the byte stream in the class file conforms to the Java Virtual machine specification. Although it is simple to say, the Java Virtual machine performs a lot of complex verification work, which can be divided into four aspects in general:

  • File format validation

  • Metadata validation

  • Bytecode verification

  • Symbolic reference verification

    Virtual machine level verification is performed on the information stored in demoClass. class loaded into the memory to ensure that the information stored in DemoClass.class does not harm the running of the Java VIRTUAL machine.

To prepare

All you do in the preparation phase is allocate memory for class variables (that is, static variables) and assign an initial value, usually zero for the data type to which the variable corresponds. At this stage, however, variables modified by final, i.e. constants, are assigned exactly at this stage.

Specifically, at this stage a in DemoClass is assigned a value of 1, and b and c are assigned 0.

parsing

The main task in this phase is to replace symbolic references in the constant pool with direct references.

Initialize the

In the previous stage, except the loading stage, in which the custom class loader can intervene in the loading process of virtual machine, the virtual machine is completely dominant in the other stages, and the initialization of classes begins according to the programmer’s will in the initialization stage. The main task of this phase is to execute the class constructor method (), and the virtual machine will ensure that the class constructor method of its parent has been executed correctly when executing the class constructor method of the class. Also, since the class is initialized only once, when multiple threads concurrently initialize the class, The VIRTUAL machine can ensure that only one thread can complete the initialization work of the class, ensuring that the thread works safely.

In the case of DemoClass, b is assigned 2 and C is assigned 3 at this stage.

4 Allocating Memory

When the class loading process is complete, or the class itself has been loaded before, the next step is for the virtual machine to allocate memory for the new objects. The amount of memory an object needs can be fully determined after the class loading process is complete. Allocating memory for an object is equivalent to allocating a proper chunk of memory from the heap. There are two main ways to allocate memory: pointer collisions and free lists.

  • Pointer collision: This way the heap memory is divided into free space and allocated space, use a pointer to the dividing line between them, when to new objects allocated memory space, equivalent to move the pointer in the direction of the free space in a and the object is equal to the size of the distance, visible this way of distribution of Java heap memory must be neat, all free space on one side, The allocated space is on the other side.

  • Free list: a list in a virtual machine maintenance, which a block of memory used to record the heap is available, free for the new object allocate memory, to find a suitable size from the list of available memory blocks, allocation update free list, after the completion of this way of free space and distribution heap memory space can be staggered.

From the above view, select the pointer collision or free list method is used to allocate memory, mainly determined by the Java heap memory is neat, and Java heap memory is neat and depends on the garbage collection algorithms, the garbage collection mechanism is involved (visible knowledge are interlinked, the programmer is never too old to learn to die!) , whether there is compression or collation after GC, etc.

At the same time, due to create the object movement is very frequent, multithreading there may be multiple threads application allocates memory space for the object at the same time, if you don’t take this time synchronization mechanism, it may lead to a thread can modify a pointer, another thread is using the original pointer allocated memory space, thus derived the two solutions: CAS is configured with retry failure and TLAB mode.

The first method is easy to understand. Multiple threads use CAS to update the pointer. In multiple threads, only one thread can update the pointer, and the other threads can re-move the pointer by retrying.

The second method is that each thread allocates a piece of memory space in advance, which is the thread local buffer TLAB. In this way, when the thread wants to allocate memory, it first obtains a piece of TLAB. When the memory space in TLAB is insufficient, the synchronization mechanism is used to apply for a piece of TLAB space, which reduces the application times of synchronous lock.

At this stage, you create a memory space in the heap for DemoClass objects, or DC object instances.

5 Initialize the value to zero

After allocating memory for an object, the virtual machine initializes the allocated chunk of memory to zero, which makes instance variables of objects in Java usable without an initial value, because the code accesses the zero value that the virtual machine allocated for the chunk of memory.

In this case, the Java virtual machine initializes the above allocated memory space to zero, so that both d and e in DemoClass are now assigned 0.

6 Set the object header

The object header is like our id card, which stores some data that identifies the object, that is, some metadata of the object. Let’s first look at the composition of the object.

After initializing the zero value, how to know which class instance the object is, we need to set the pointer to the type information in the method area, and set the relevant information in the object Mark Word, which is completed in this stage.

7 Initialize the instance object

In this step, the virtual machine calls the instance constructor method (), which initializes the object according to our programmer’s wishes. In this step, the constructor is called to complete the initialization of the instance object.

In this case, d of DemoClass is assigned 4 and e is assigned 5.

8 Create a reference and push it

Execution to this step, already exist in heap memory is complete to create objects, but as we know, in Java using the object is referenced by virtual machine in the stack to obtain object properties, call object method, so this step will create the object reference, and pressure, such as virtual machine stack eventually return reference for our use.

In this case, an object is being pushed onto the stack, and an assignment is returned to DC, at which point an object is created.

The complete flow of object instantiation

Based on the above discussion, let’s review the entire process of object instantiation: