Java virtual machine garbage collection mechanism, generational storage of heap memory, loading and unloading of classes

==============================================

                                    1: Memory model

==============================================

 

Thread shared area: heap (heap) and method area (Method Area)

Thread private: program counter, java virtual machine stack, local method stack.

Heap (heap): the storage location of new objects (excessive storage will cause memory overflow)

Method area: store static attributes and constants (excessive storage will cause memory overflow)

 

Program counter: can be understood as recording which line or instruction the current thread executes. So that when the thread switches back, execution can continue from the current instruction.

Java virtual machine: Store stack frames. It can be understood that every time a method is called, a stack frame is put into the virtual machine. Pushing too much on the stack will cause the stack to overflow (that is, the method call level is too deep).

Native method stack: Similar to the virtual machine, but this stack is used to store the stack frame of the Native method.

==============================================

                                    2: Memory module division

==============================================

 

[ 1: Recovery algorithm ---- Generational collection algorithm ]

        [ Reachability analysis algorithm ] Algorithm for marking whether objects need to be recovered

        Object references refer to each other using the reference chain as a path. If the chain of references to an object is not connected to any of the root node (GC Roots) , it shows that this object is useless, that need to be recycled. The so-called root node references are static attributes, constant attributes, and stack frame references. There are also references to variables (don’t say member variables) referenced by Native methods. If there is no reference to these four, it means that the object is useless.

       

         The life cycle of the object is divided into: the young generation and the old generation

------- Cenozoic : Adopt the replication algorithm. (Algorithm for low object survival rate)

--------------------  Replication algorithm: Divide the memory into two, divided into two areas of the same size. Only one area is used at a time. When this area is nearly used up, all the surviving objects (accessibility analysis algorithm) in this area will be copied to another area, and then this half area will be cleared. Each time, the entire half area is recovered.

                                           Disadvantages : Only half of the memory area can be used each time, and the memory space usage rate is too low

                                            Advantages : high efficiency, only half of the area is recovered each time. There is no need to consider the problem of memory fragmentation, because it will be rearranged after copying, and the remaining internal

                                                       The storage space is arranged completely and continuously .

 

------- Old age : use mark-clear algorithm or mark-sort algorithm (algorithm used for high object survival rate)

-------------------- Mark-clear algorithm: Mark the objects to be recycled through the reachability analysis algorithm, and then the marked objects will be recycled by the GC thread.

                                           Disadvantage 1> efficiency problem, the mark and efficiency are not clear

                                           Disadvantage 2>  Space problem, a large number of discontinuous memory fragments will be generated after clearing. If memory space is to be allocated to a large object later, when these memory fragments are not enough to have enough space, the GC will be reclaimed again.                                      

-------------------- Marking-sorting algorithm: Mark the objects to be recycled through the reachability analysis algorithm, and then the marked objects will be recycled by the GC thread. It is an enhanced version of "Marker Removal Algorithm". Do not clean up the recyclable objects directly, but move the surviving objects to one side, so that all surviving objects are sorted continuously in the memory space. Then directly clean up the useless objects outside the boundary.

                                           Advantage 1>  solves the problem of memory fragmentation

                                         

---------------------[ Mark-Clear Algorithm ] Sample image

 

--------------------- [ Marking-Arrangement Algorithm ] Example image

 

[ 2: Garbage Collector-Recovery Mechanism ]

The garbage collector scans the object that needs to be recycled, and the finalize() of this object has never been called, it will call the finalize() of the object. If the finalize() object is reconnected to the root node (for example: assigning the object to a static variable), the object will not be recycled at this time. But if the finalize() method of the object has already been called, the finalize() will not be called again, and the object will be recycled directly.

[ 3: Memory allocation and recycling strategy ]

1: Partition

The memory allocation of newborn objects is divided into: Eden  >  Survivor  > The   priority of the elderly area     decreases sequentially

New area: Eden and Survivor (copy and recovery algorithm)

Older area: Older area (marking-sorting and recycling algorithm)

 

Note: Not all objects will be stored in the new area first. For example, if an object is particularly large, it will directly enter the old area  .

Therefore, avoiding the creation of large objects will trigger the garbage collector to collect garbage in advance to provide enough continuous space to place large objects.

(The Java virtual machine can set the boundaries of large objects through parameters). More than put it directly into the elderly zone.

 

[ 2: The movement of the object in the memory area ]

<Rule 1> The    age counter, every time it is scanned by the garbage collector, the age is +1. Eden is swept once and will move to the Survivor area if it survives, and if the Survivor area is swept 15 times, it will move to the old area. Of course, the parameters of these limits can be controlled.

<Rule 2> The     age judging rule is not unique. If the sum of the memory occupied by all objects of the same age in the Survivor area is greater than half of the Survivor space, then objects older than this age will be moved to the elderly area.

<Rule 3>

1> The object will only exist in the Eden area and the From area of ​​Survivor at first, and the "To" of Survivor is empty.

2> Immediately after GC, all the surviving objects in the Eden area will be copied to "To", and in the "From" area, the surviving objects will decide where to go according to their age. Objects whose age reaches the age threshold will be moved to the old generation, and objects that have not reached the threshold will be copied to the "To" area.

3> Minor GC will repeat this process until the "To" area is filled, and after the "To" area is filled, all objects will be moved to the old generation.

 

 

==============================================

                                    2: Class loading

==============================================

The loading of classes is divided into five major steps:

1: Load

1: Obtain this type of binary stream (respectively from: zip, network (applet), run-time generation (dynamic proxy))

2: Turn this flow into a method to run data structure

3: Generate the Class object of this class as the data access interface of this class in the method area

2: Connect

              Segmentation: verification, preparation, analysis

Verification : Verify whether the encoding conforms to UTF-8, whether the constant type is supported, etc.

Preparation : allocate memory, initialize variables

Resolution : The virtual machine replaces constant pool symbol references with direct references

 

3: Initialization】   

The last step of class loading

4: Use

Use is to use object properties

5: Uninstall

Uninstall, can be understood as the reference process is killed

 

[ The relationship between class and class loader ]

Comparing whether two classes are equal or not, only makes sense if the two classes are loaded by the same class loader. Otherwise, even if the two classes originate from the same class file and are loaded on the same virtual machine, as long as the loader that loads them is different, then the two classes must not be equal.

Java determines whether a class is equal (equals() method, isAssignableFrom() method, isInstance() method returns the result)

 

From the perspective of the Java virtual machine, there are only two types of loaders:

1: Start the class loader

2: Other class loaders

 

The class loading mechanism recommended by Java designers to developers is: the parent delegation model is          as shown in the figure below:


 

The figure above shows the parent delegation model   except for the startup class loader at the top, other loaders have their own parent class loaders. The parent-child relationship here is generally not an integrated relationship, but takes the code of the parent loader by using a composite relationship.

 

[ Working process of the parent delegation model ]

        If a class loader receives a loading request, it will first throw the request to the parent class to complete it. This is the case for each level of loader, so all requests will eventually be passed to the top startup class loader, only When the parent class loader reports that it cannot complete the loading task, the child class loader will try to load it by itself.

Benefits

         This loading mechanism has a hierarchical relationship of priority. When trying to load a class, it will eventually be passed to the top startup class loader, which guarantees the uniqueness of the class in the program. For example: For example, to load java.lang.String, stored in rt.jar, it will eventually be delegated to the top startup class loader to complete the loading task, so the String class is in each class loader environment in the program Both are the same class. On the contrary, if there is no parental delegation model, each class loader loads a class separately, take java.lang.String as an example, and each class loader loads the String class, then there will be multiple different String classes in the program , It will be very confusing, and the most basic behavior in the java program cannot be guaranteed.

 

 

 

 

Guess you like

Origin blog.csdn.net/Leo_Liang_jie/article/details/90379533