java runtime data area-----object creation

Object creation: When the virtual machine encounters a new keyword, it will first go to the constant pool to check whether there is a symbolic reference of this class, and check whether the class represented by this class has been loaded, parsed, and initialized. If not, it must be Perform the corresponding class loading process first. After the class loading process is passed, the next step is to allocate memory for the new object (divide a memory area from the java heap).

1 If the memory in the java heap is regular, we call it the A area on the left, which stores the memory that has been used, and the right side, which we call the B area, which stores the memory area that has not been used, and the indicator in the middle. Move a small segment to the right, this way we call pointer collision.

2 If the internal training area in the java heap is scattered, then simple pointer collision cannot be performed. The virtual machine must maintain a list to record which memory blocks are available, and find a large enough block to allocate to the object instance at the time of allocation. And update the records on the list, this allocation method becomes a free list.

The choice of the above method is determined by whether the Java heap is regular, and whether the Java heap is regular is determined by whether the garbage collector used has the compaction function.

The creation of objects is a very frequent process in the JVM. It is possible that memory is being allocated to object A, the pointer is beautiful and can be modified, and object B also uses the original pointer to allocate memory, which is very unsafe. , there are two solutions to this problem.

1 is to synchronize the action of allocating memory---using CAS coupled with failure retry to ensure the atomicity of the update operation.

2. The action of memory allocation is divided into different spaces according to threads, that is, each thread pre-allocates a small piece of memory in the java heap, which becomes a local thread allocation buffer.

When the memory allocation is completed, the virtual machine needs to initialize the allocated space to 0. Next, the created object needs to be identified to a certain extent. For example, this object is an instance of that class. Hash code, GC generation age of the object, etc. These information are stored in the java object cast.

After the above work is completed, from the point of view of the virtual machine, a new object will be created, but from the point of view of the java program, the creation of the object has just begun, and the <init> method has not been executed yet. Some fields are still 0. After the new instruction is executed, the init method will be executed immediately.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325993151&siteId=291194637