The premise of garbage collection is to determine if the object is alive, the object will be recycled when it is no longer alive, and here are 2 ways to judge it.
Reference counting Method:
Mainstream Java virtual machines do not use reference counting to manage memory, and the important reason is that the problem of circular references is difficult to solve.
Accessibility Analysis Method:
The basic idea of this algorithm is: through a series of objects called "GC Roots" as the starting point, search down, traversed by the path called the reference chain, when the object to the GC Roots no reference chain, It is considered that the object can be recycled.
In Java, the objects that can be used as GC Roots include:
1"objects referenced in the virtual machine stack
2. Objects referenced by static properties in the method area
3. The object referenced by a constant in the method area
4.JNI referenced object
After JDK1.2, the reference of the object can be divided into strong reference, soft reference, weak reference, virtual reference 4 , the strength of the reference is reduced in turn.
A reference to a strong reference, implemented by the new object.
Soft references, which are not reclaimed when memory is sufficient, are recycled when the memory is low.
Weak references, regardless of whether the memory is sufficient will be recycled.
Virtual references, which cannot be used to obtain an object instance through a virtual reference, the sole purpose of setting a virtual reference for an object is to receive a system notification when the object is reclaimed.
Reclamation in the method area consists of 2 parts: Obsolete constants and useless classes.
For example, a constant pool has a string constant named "ABC", but is not referenced by any strings in the system, it is recycled.
A class needs to meet the following 3 conditions to be defined as useless classes:
1"All instances of this class have been recycled
2"The ClassLoader that loaded the class have been recycled
3 The Class object is not referenced anywhere and cannot be accessed from anywhere through reflection
Garbage collection algorithm
Mark Clear Method
There are 2 problems with this algorithm:
First, the efficiency is not high, marking and eliminating 2 processes is not very efficient
The second is the problem of generating a large number of fragments, and then allocating memory to large objects may be due to the inability to find large enough contiguous memory, and a garbage collection.
Replication Algorithms
In-depth understanding of Java Virtual Machines Learning notes (ii)