In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the garbage collector and object survival law in the Java virtual machine". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the garbage collector and object survival law in the Java virtual machine".
I. Overview
There is significant uncertainty in both the Java heap and the method zone:
1. Multiple implementation classes of an interface may require different memory, and different conditional branches executed by a method may also require different memory.
2. Only when we are running can we know which objects and how many objects the program will create. The allocation and recovery of this part of memory is dynamic.
Second, the object is dead? 1. Citation counting method
Add a reference counter to the object, which is incremented by one whenever a place references it; when the reference expires, the counter is subtracted by one; objects with zero counters at any time can no longer be used.
Although the reference counter takes up some extra memory space to count, the principle is simple and the judgment efficiency is very high.
Why don't mainstream Java virtual machines use reference counters to manage memory?
There are many exceptions to the seemingly simple algorithm of reference counting, which must be combined with a lot of extra processing to ensure the correct work. For example, simple reference counting is difficult to solve the problem of circular reference between objects.
Defects in reference counters
/ * * @ Author: yky * @ CreateTime: 2020-12-13 * @ Description: defect of the reference counter * / public class ReferenceCountingGC {public Object instance = null; private static final int _ 1MB = 1024 * 1024; / * the only function of this member variable is to occupy memory * / private byte [] bigSize = new byte [2 * _ 1MB]; public static void testGC () {ReferenceCountingGC objA = new ReferenceCountingGC (); ReferenceCountingGC objB = new ReferenceCountingGC (); objA.instance = objB ObjB.instance = objA; / / whether GC,objA and objB can be recycled System.gc ();}}
Run the code to check the log information and find that both objects are recycled by the virtual machine and not abandoned because the two references each other-> the Java virtual machine does not use the counting algorithm to determine whether the object is alive.
2. Reachability analysis algorithm
The core idea of the algorithm: through a series of root objects called "GC Roots" as the starting node set, from these nodes, search downward according to the reference relationship, the path of the search process is called "reference chain". If there is no reference chain connection between an object and GC Roots (in graph theory, when it is unreachable from GC Roots to this object, it is proved that this object can no longer be used)
Objects obj5, obj6, and obj7 are related, but they are unreachable to GC roots, so they are judged to be recyclable objects.
In the Java language, objects that can be used as GC Roots include the following:
Reference objects in the virtual machine stack (local variables in the stack), such as parameters, local variables, temporary variables, etc., used in the method stack where each thread is called.
An object referenced by a static property of a class in the method area, such as a reference type static variable of the Java class
An object referenced by a constant in a method area, such as a reference in a string constant
Objects referenced by the local method stack total JNI (Navicat method)
References within the Java virtual machine
All objects held by the synchronization lock (synchronized keyword)
JMXBean that reflects the internal situation of the Java virtual machine, callbacks registered in JVMTI, native code caching, etc.
Depending on the garbage collector selected by the user and the area of memory currently reclaimed, other objects can be added "temporarily".
No matter which algorithm is used to judge whether the object is alive or not, it has something to do with "reference".
1) strong citation
Refers to the reference assignment that is ubiquitous between program code, Object obj = new Object (); this reference relationship.
In any case, as long as the strong reference relationship exists, the garbage collector will not recycle the referenced object
2) soft reference
Used to describe objects that are useful but not necessary. As long as the objects associated with the soft reference are listed in the scope of recycling for a second collection before the memory overflow occurs in the system, the exception of memory overflow will be thrown if there is not enough space for this collection.
After JDK1.2, SoftReference class is provided to implement soft reference:
Soft reference objects, which are cleared at the discretion of the garbage
Collector in response to memory demand. Soft references are most often used
To implement memory-sensitive caches.
3) weak reference
Weak references are also used to trace non-essential objects, which are weaker than soft references. Objects associated with weak references can only survive until the next garbage collection occurs. When the garbage collector starts to work, no matter whether the current memory is sufficient, objects associated with weak references will be recycled.
The WeakReference class after JDK1.2 is used to implement weak references:
Weak reference objects, which do not prevent their referents from being
Made finalizable, finalized, and then reclaimed. Weak references are most
Often used to implement canonicalizing mappings.
4) Virtual reference
Also known as "ghost citation" and "phantom citation", the weakest citation relationship.
Whether an object has a virtual reference has no effect on its survival time at all, and it is impossible to obtain an instance of an object through a virtual reference.
The only purpose of setting a virtual reference for an object is to receive a system notification when the object is reclaimed by the collector
PhantomReference class to implement virtual references:
Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used to schedule post-mortem cleanup actions.
The application needs to read a large number of local images:
If every time the picture is read from the hard disk, it will seriously affect the performance; solution: [soft reference or weak reference]
Map imp = new HashMap
4. Live or die?
After the reachability analysis, the object is not necessarily dead. After the reachability analysis, it is found that there is no reference chain connected to GC Roots.
The object is marked for the first time; to determine whether the object needs to execute the finalize () method (either the finalize () method has been called by the virtual machine or the finalize () method is not overridden, it is not considered necessary to execute the finalize () method)
The object is stored in the F-Queue queue, and the lower priority Finalizer thread will execute it; Gc will mark the object in the queue again, and if the object does not save itself in the finalize method, it will be marked for collection
The finalize method saves itself by re-establishing a connection with any object on the reference chain, such as assigning its own this to a member variable of a class or object.
The results are as follows:
Finalize method executed!
Yes,I am still alive:)
No, i am dead: (
The use of this method to save the object is not encouraged, because it is expensive and uncertain, and the sequence cannot be guaranteed.
All the work that the finalize method can do, try-finally can also do better and more timely, so I hope to forget the existence of this method.
5. Recovery method area
Many people think that the method zone (or the metaspace or permanent generation in the HotSpot virtual machine) does not have garbage collection behavior. The Java virtual machine specification does say that virtual machines can not be required to implement garbage collection in the method area, and the "performance-to-price ratio" of garbage collection in the method area is generally low: in the heap, especially in the new generation, conventional applications can generally reclaim 70% or 95% of the space after a garbage collection. The garbage collection efficiency of the permanent generation is much lower than this.
There are two main parts of garbage collection in the method area: abandoned constants and types that are no longer used.
Recycling obsolete constants is very similar to recycling objects in the Java heap. Take the recovery of literals in a constant pool as an example:
If a string "Java" has entered the constant pool, but the current system does not have a string object whose value is "Java", in other words, no String object refers to the "Java" constant in the constant pool, and there is no other place to reference this literal quantity, if memory collection occurs at this time, and if necessary, the "Java" constant will be cleaned out of the constant pool by the system.
Symbolic references to other classes (interfaces), methods, and fields in the constant pool are similar.
It is easy to determine whether a constant is an "obsolete constant". The conditions for determining whether a class is a "useless class" are much harsher. A class needs to meet the following three conditions to be considered a "useless class":
All instances of the class have been recycled, that is, no instances of the class exist in the Java heap.
The ClassLoader that loaded the class has been recycled.
The corresponding java.lang.Class object of this class is not referenced anywhere, and its methods cannot be accessed anywhere through reflection.
The virtual machine can recycle the useless classes that meet the above three conditions, which only means "allowed", not like the object, which is bound to be recycled if it is not used. In scenarios where bytecode frameworks such as reflection, dynamic proxy and CGLib are widely used, and frequently customized ClassLoader such as JSP and OSGi are generated dynamically, the virtual machine needs to have the function of class unloading to ensure that it will not cause excessive memory pressure by the method area.
Thank you for reading, the above is the content of "what is the garbage collector and object survival law in the Java virtual machine". After the study of this article, I believe you have a deeper understanding of what the garbage collector and object survival law in the Java virtual machine is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.