Garbage collector for Java Virtual machines (7)

Source: Internet
Author: User
Tags throwable

I. Introduction to Java garbage collection

(1) The various parts of the Java memory runtime area, where the program counter, virtual machine stack, local method stack three regions are born with threads, and the stack frames in the stack execute the stack and stack operations in a methodical manner as the method enters and exits.

(2) How much memory is allocated per stack frame is basically known when the class structure is determined (although some optimizations are made by the JIT compiler at run time), Therefore, there is certainty in memory allocation and recycling in these areas. There is no need to think too much about recycling in these areas, because when the method ends or the thread ends, the memory is naturally recycled.

(3) While the Java heap and the method area are different, multiple implementation classes in an interface may require different memory, multiple branches in one method may require different memory, we can only know when the program is running, which objects will be created, this part of memory allocation and recycling is dynamic, The garbage collector is concerned about this part of the memory.

Second, a method of garbage collection: Reference counting algorithm

When we interview, when asked how to determine whether the object is alive, we may answer: Add a reference counter to the object, each time there is a place to reference it, the counter value is added 1, when the reference fails, the counter value is reduced by 1, any time the counter is 0 of the object is impossible to be used again.

The answer is correct, but the Java language does not use this method as a garbage collection mechanism. Reference counting algorithm, the decision efficiency is also very high, in most cases it is a good algorithm, not to use the reason, the most important of which is that it is difficult to solve the problem of Mutual circular reference between objects.

For example:
Both objects Obja and OBJB have field instance, the assignment order obja.instance = objb and objb.instance = Obja, and in addition, these two objects have no reference, in fact, these two objects are no longer accessible, but they are referenced by each other Each other, resulting in their reference count not being 0, the reference counting algorithm cannot tell the GC collector to reclaim them.

after the/** * TESTGC () method is executed, will obja and OBJB be GC? */ Public  class referencecountinggc {     PublicObject instance =NULL;Private Static Final int_1MB =1024x768*1024x768;/** * The only meaning of this member property is to occupy a bit of memory so that it can be seen in the GC log whether it has been recycled * /    Private byte[] Bigsize =New byte[2* _1MB]; Public Static void TESTGC() {REFERENCECOUNTINGGC Obja =NewREFERENCECOUNTINGGC (); REFERENCECOUNTINGGC OBJB =NewREFERENCECOUNTINGGC ();        Obja.instance = OBJB;        Objb.instance = Obja; Obja =NULL; OBJB =NULL;//Assuming GC is occurring on this line, can obja and objb be recycled? System.GC (); }}

From the top of the code running results, it means that the virtual machine does not recycle them because the two objects are referenced to each other, which also indicates from the side that the virtual machine does not use the reference counting algorithm to determine whether the object is alive or not.

Third, Root search algorithm

It is known here that the Java garbage collection mechanism uses the "root search algorithm" to determine whether an object survives, starting from these nodes to search down, the path that the search passes is called the reference chain (Reference Chain), when an object to the GC Roots It is not possible to prove that this object is not available when no reference chain is connected (in the case of graph theory, from GC Roots to the object unreachable).

As shown, objects 5, 6, and object 7 are associated with each other, but they are not accessible to GC Roots, so they will be judged as recyclable objects.

In the Java language, the objects that can be used as GC Roots include the following:
(1) The referenced object in the virtual machine stack (the local variable table in the stack frame).
(2) The object referenced by the class static property in the method area.
(3) The object that the constant in the method area refers to.
(4) The referenced object of JNI (that is, generally speaking, the Native method) in the local method stack.

Iv. Types of references

Our understanding of references may be simple: if the value stored in the data of the reference type represents the starting address of another piece of memory, it is said that this memory represents a reference. But the book says this way is too narrow, an object in this definition can only be referenced or not cited in two states, for how to describe some "tasteless, discard" object is powerless. We want to describe a class of objects that can be kept in memory when the memory space is sufficient, and if they are still very tense after being garbage collected, you can discard those objects . Many of the system's caching capabilities are consistent with this scenario.

The general reference types are divided into strong references (strong Reference), soft references (Soft Reference), weak references (Weak Reference), virtual references (Phantom Reference), and four of these four reference intensities gradually weaken in turn.

Below are four types of introductions:

(1) A strong reference is a common reference in program code, such as "Object obj = new Object ()", as long as a strong reference exists, the garbage collector never reclaims the referenced object.

(2) soft references are used to describe some objects that are also useful, but are not required. For objects associated with soft references, * * Within the system will occur
Before the overflow exception is stored, these objects are listed in the collection scope and recycled for a second time. If this recovery is still not enough
Memory overflow exception is thrown. After JDK 1.2, the SoftReference class was provided to implement soft references.

(3) A weak reference is also used to describe a non-required object, but its strength is weaker than a soft reference, and the object associated with the weak reference only survives until the next garbage collection occurs. * * When the garbage collector is working, it will reclaim only weak references, regardless of the current memory adequacy
The associated object * *. After JDK 1.2, the WeakReference class was provided to implement weak references.

(4) A virtual reference , also known as a phantom reference or phantom Reference, is the weakest reference relationship. Whether an object has a virtual reference exists, does not affect its lifetime at all, and cannot obtain an object instance through a virtual reference. Sets a virtual reference off for an object
The only purpose of the joint is to be able to receive a system notification when the object is reclaimed by the collector. After JDK 1.2, the Phantomreference class is provided to implement the virtual reference.

Five, two times the garbage collection time mark

Objects that are unreachable in the root search algorithm are not "dead", while they are temporarily in the "probation" stage, * * to truly DECLARE
Tell an object to die, at least two times. Marking Process * *: If the object is found to be not connected to GC Roots after root search
Reference chain, then it will be marked for the first time and filtered by the condition that it is necessary for this object to perform finalize ()
Method. * * When the object does not overwrite the Finalize () method, or the Finalize () method has been called by the virtual machine, the virtual machine will either
are considered "No need to execute". **

If the object is judged to be necessary to execute the Finalize () method, then the object will be placed in a f-queue named
Queue, and is later executed by a low-priority Finalizer thread that is automatically created by the virtual machine. Here the so-called "practice
Line "means that the virtual opportunity triggers this method, but does not promise to wait for it to run to the end. The reason for this is that if an object is in the
A slow execution in the Finalize () method, or a dead loop (more extreme), will most likely result in the F-queue queue
Other objects are permanently waiting, even causing the entire memory recovery system to crash. Finalize () method is an object that escapes the fate of death
Last chance, later the GC will make a second small-scale mark on the objects in the F-queue if the object is to be in Finalize ()
To successfully save yourself-just re-associate with any object on the reference chain, such as assigning yourself (this keyword)
Value to a class variable or to a member variable of an object, which is removed from the collection that is "about to be recycled" at the time of the second token, if the object
The time has not escaped, then it really is not far away from the death.

The next piece of code we can see that the Finalize () of an object is executed, but it can still survive.

/** * This code demonstrates two points: * 1. Objects can be saved by the GC itself. * 2. This chance of self-help is only one time, because the Finalize () method of an object is called only once by the system. */ Public  class finalizeescapegc {     Public StaticFINALIZEESCAPEGC Save_hook =NULL; Public void isAlive() {System.out.println ("Yes, I am still alive"); }@Override    protected void Finalize()throwsThrowable {Super. Finalize (); System.out.println ("Finalize Mehtod executed!"); Finalizeescapegc.save_hook = This; } Public Static void Main(string[] args)throwsthrowable {Save_hook =NewFINALIZEESCAPEGC ();//objects successfully saved themselves for the first timeSave_hook =NULL; System.GC ();//Because the Finalizer method has a low priority, pause for 0.5 seconds to wait for itThread.Sleep ( -);if(Save_hook! =NULL) {save_hook.isalive (); }Else{System.out.println ("No, I am dead"); }//The code below is exactly the same as above, but this time the rescue failed.Save_hook =NULL; System.GC ();//Because the Finalizer method has a low priority, pause for 0.5 seconds to wait for itThread.Sleep ( -);if(Save_hook! =NULL) {save_hook.isalive (); }Else{System.out.println ("No, I am dead"); }    }}

The results of the implementation are as follows:

finalize mehtod executed!yes, i am still aliveno, i am dead

The code has two pieces of exactly the same code fragment, the result is a successful escape, a failure, this is because any of the object's Finalize () method will only be automatically called by the system once, if the object faces the next collection, its Finalize () method will not be executed again, So the second code of the self-rescue operation failed.

Six, recovery method area

(The following is the book directly to find, do not understand)

Many people think that the method area (or the permanent generation in the HotSpot virtual machine) is not garbage collected, and the Java virtual machine specification
Did say that you can not require virtual machines to implement garbage collection in the method area, and the "Price/performance" Comparison of garbage collection in the method area
Low: In the heap, especially in the Cenozoic, the general application of a garbage collection generally can reclaim 70%~95% space, and never
Giude's garbage collection efficiency is much lower than this. The garbage collection of the permanent generation mainly recycles two parts: obsolete constants and useless classes. Reclaiming obsolete constants is very similar to reclaiming objects in the Java heap. For example, if a string "ABC" has entered a constant pool in the case of a constant pool literal, the current system does not have any string object called "abc", in other words, there is no string object referencing the "ABC" constant in the constant pool. There is no other place to quote this literal, and if a memory recycle occurs at this time, and if necessary, the "ABC" Constant will be "please" out of the constant pool. The symbolic references to other classes (interfaces), methods, and fields in a constant pool are similar. It is relatively straightforward to determine whether a constant is an "obsolete constant", and the condition to determine whether a class is a "useless class" is much more harsh. Classes need to meet the following 3 conditions to be considered "useless classes": All instances of the class have been reclaimed, that is, no instances of the class exist in the Java heap. The ClassLoader that loaded the class have been recycled.

The corresponding Java.lang.Class object of this class is not referenced anywhere and cannot be accessed from anywhere by reflection.
Method. Virtual machines can recycle the useless classes that meet the above 3 criteria, which is simply "yes", not the same as the object, and will inevitably be recycled if not used. Whether the class is recycled, the HotSpot virtual machine provides control of the-XNOCLASSGC parameters and can also
To view load and unload information for a class using-verbose:class and-xx:+traceclassloading,-xx:+traceclassunloading.
A large number of scenes using bytecode frameworks such as reflection, dynamic proxies, CGLIB, and dynamic generation of JSP and OSGi are frequently
The custom ClassLoader scenario requires the virtual machine to have the class offload function to ensure that the permanent generation does not overflow.

Garbage collector for Java Virtual machines (7)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.