Java Virtual machine Note (ii): GC garbage Collection

Source: Internet
Author: User

Why you should know about GC

We all know that Java developers do not need to be concerned about the recycling of objects in the development process, because the Java virtual machine causes it to automatically reclaim the failed garbage objects. So why do we have to learn about GC and memory allocation?

The answer is simple: when we need to troubleshoot various memory overflows, memory leaks, and when the garbage collector becomes a bottleneck for the system to achieve higher concurrency, we need to implement the necessary monitoring and tuning of these "automated" technologies.

What objects are recycled

We know that in the Java Memory Runtime data region, the virtual machine stack, the local method stack, and the program counter are thread-isolated data areas that are born with threads and are out of thread, and stack frames in the stack are methodically executing the stack and stack operations as the method enters and exits. The amount of memory allocated in each stack frame is basically known when the class structure is determined. As a result, the memory allocations and recoveries in these areas are deterministic, and 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.

While the method area and heap are data areas shared by all threads, multiple implementations in one interface may require different memory, and multiple branches in one method may require different memory, and we will only know what objects are created when the program is running, and this portion of memory allocation and recycling is dynamic. The garbage collector is concerned with this part of the memory.

How to tell if objects can be recycled 1. Reference counting Method

Principle: Add a reference counter to the object, and whenever there is a place to refer to it, the counter value is incremented by 1, and when the reference fails, the counter value is reduced by 1, and any object with counter 0 at any time is impossible to be used again.

Advantages: Simple to achieve, high efficiency judgment.

Disadvantage: It is difficult to solve the problem of circular references between objects. ( This method is not used in mainstream Java Virtual machines ).

For a simple example, look at the TESTGC () method in the Code listing: Objects Obja and OBJB have field instance, assignment makes obja.instance = objb and objb.instance = Obja, and beyond that, there are no references to these two objects. In fact, these two objects are no longer accessible, but because they reference each other, resulting in their reference count is not 0, so the reference counting algorithm Cannot notify the GC collector to reclaim them.

1 /**  2 * After the TESTGC () method is executed, will obja and OBJB be GC? 3  * @authorZzm4  */  5  Public classREFERENCECOUNTINGGC {6  7    PublicObject instance =NULL; 8  9   Private Static Final int_1MB = 1024 * 1024; Ten   One   /**   A * The only meaning of this member property is to occupy a bit of memory so that it can be seen in the GC log if it is recycled -    */   -   Private byte[] Bigsize =New byte[2 *_1MB];  the   -    Public Static voidTESTGC () { -REFERENCECOUNTINGGC Obja =NewREFERENCECOUNTINGGC ();  -REFERENCECOUNTINGGC OBJB =NewREFERENCECOUNTINGGC ();  +Obja.instance =OBJB;  -Objb.instance =Obja;  +   AObja =NULL;  atOBJB =NULL;  -   -    //Suppose Gc,obja and OBJB can be recycled in this line?  - System.GC ();  -   }   -}

Run results

1[Full GC (System) [tenured:0k->210k (10240K), 0.0149142 secs] 4603k->210k (19456K), [perm:2999k->2999k (21248K) ], 0.0150007 secs] [times:user=0.01 sys=0.00, real=0.02secs]2 Heap3DefNewGeneration Total 9216K, used 82K [0x00000000055e0000, 0x0000000005fe0000, 0x0000000005fe0000)  4Eden space 8192K, 1% used [0x00000000055e0000, 0x00000000055f4850, 0x0000000005de0000)  5From space 1024K, 0% used [0x0000000005de0000, 0x0000000005de0000, 0x0000000005ee0000)  6To space 1024K, 0% used [0x0000000005ee0000, 0x0000000005ee0000, 0x0000000005fe0000)  7Tenured generation total 10240K, used 210K [0x0000000005fe0000, 0x00000000069e0000, 0x00000000069e0000)  8The space 10240K, 2% used [0x0000000005fe0000, 0x0000000006014a18, 0X0000000006014C00, 0x00000000069e0000)  9Compacting Perm Gen Total 21248K, used 3016K [0x00000000069e0000, 0x0000000007ea0000, 0x000000000bde0000)  TenThe space 21248K, 14% used [0x00000000069e0000, 0x0000000006cd2398, 0x0000000006cd2400, 0x0000000007ea0000)   OneNo shared spaces configured.

It is clear from the running results that the GC log contains "4603k->210k", which means that the virtual machine is not recycled because the two objects are referencing each other, which also indicates from the side that the virtual machine does not determine whether the object is alive by reference counting algorithms.

2. Accessibility algorithm (root search algorithm)

Principle: Through a series of objects called "GC Roots" as the starting point, starting from these nodes to search down, the path of the search is called the reference chain, when an object to the GC Roots no reference chain connected (in the words of graph theory, that is, from the GC Roots to this object unreachable), proves that this object is not available.

In the figure, 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:

    • The object referenced in the virtual machine stack (the local variable table in the stack frame).
    • The object referenced by the class static property in the method area.
    • The object referenced by the constant in the method area.
    • The object referenced by JNI (that is, generally speaking, the native method) in the local method stack.

References to Objects

Whether the reference count of the object is judged by the reference counting algorithm or whether the reference chain of the object can be reached by the root search algorithm, it is related to the reference to determine whether the object is alive.

After JDK 1.2, Java extends the concept of references into strong references (strong Reference), soft references (Soft Reference), weak references (Weak Reference), virtual references (Phantom Reference) Four species, these four kinds of reference strength gradually weakened.

1. Strong references (strongreference)

Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it. As follows:

Object o=New object (); // Strong references

When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues. If not, use the following method to weaken the reference, as follows:

o=null; // Help garbage collector Reclaim this object

Explicitly setting o to null, or exceeding the life cycle of an object, the GC considers that the object does not have a reference and can then reclaim the object. The exact time to collect this depends on the GC algorithm.

2. Soft Reference (SoftReference)

Used to describe some objects that are also useful, but are not required.

If an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. soft references can be used to implement memory-sensitive caches.

1 string str=new string ("abc");                                     // Strong References 2 softreference<string> softref=new softreference<string> (str);     // Soft References

When memory is low, it is equivalent to:

1 If (JVM. Low memory ()) {2    null;  // convert to Soft reference 3    // garbage collector for recycling 4 }

Soft references have important applications in practice, such as the browser's Back button. When you press back, will the page content that is displayed on the back of this fallback be re-requested or removed from the cache? This depends on the specific implementation strategy.

(1) If a Web page is recycled at the end of the browse, then pressing back to view the previously browsed page needs to be rebuilt

(2) If you store your browsed pages in memory, it can cause a lot of wasted memory and even memory overflow.

Soft references can be used at this time.

1Browser prev =NewBrowser ();//get page to browse2SoftReference sr =NewSoftReference (prev);//after browsing is complete, set to soft reference3 if(Sr.get ()! =NULL){ 4Rev = (Browser) sr.get ();//Has not been recovered by the collector, directly obtained5}Else{6Prev =NewBrowser ();//because of the memory crunch, the soft-referenced objects are recycled7SR =NewSoftReference (prev);//re-build8}

This will be a good solution to the actual problem.

A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it.

3. Weak references (WeakReference)

is also used to describe a non-required object, but its strength is weaker than soft reference, and the object associated with the weak reference only survives until the next garbage collection occurs. When the garbage collector is working, the objects associated with a weak reference are reclaimed regardless of whether the current memory is sufficient. After JDK 1.2, the WeakReference class was provided to implement weak references.

The difference between a weak reference and a soft reference:

Objects that have only weak references have a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.

String Str=new string ("abc"); weakreference<string> abcweakref = new weakreference<string> (str); str=null;

When the garbage collector is scanned for recycling, it is equivalent to:

str = NULL; System.GC ();

If this object is used occasionally and wants to be available at any time when it is used, but does not want to affect the garbage collection of this object, then you should use Weak Reference to remember this object.

The following code causes STR to become a strong reference again:

String  ABC = abcweakref.get ();

A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.

When you want to refer to an object, but this object has its own life cycle, you do not want to intervene in the life cycle of this object, you are using weak references.

 

4. Virtual references (phantomreference)

"Virtual Reference" as the name implies, is the same as a dummy, also known as Phantom Reference or phantom reference, it is the weakest of a 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. The only purpose of setting a virtual reference association for an object is to expect 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.

A virtual reference differs from several other references, and the virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.

Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory.

Summary of 4 types of citations

The level of JAVA4 references is from highest to lowest:

Strong references > Soft references > Weak references > virtual references

Look at the differences between them in the garbage collection table:

Two-time tagging process for object death

Even those unreachable in the Accessibility analysis algorithm are not "dead", when they are temporarily in the "probation" stage, to truly declare an object to die, at least to undergo a re-tagging process.

The premise of tagging is that the object finds no reference chain connected to the GC roots after the accessibility analysis.

1). Mark the first time and filter once.

The criteria for filtering is whether this object is necessary to perform a finalize () method.

When the object does not overwrite the Finalize method, or the Finzlize method has been called by the virtual machine, the virtual machine treats both cases as "no need to execute" and the object is recycled.

2). Second time Mark

If this object is judged to be necessary to execute the Finalize () method, then this object will be placed in a queue named F-queue, and then executed by a low priority finalizer thread that is automatically established by a virtual machine later. The so-called "execution" here refers to the virtual opportunity to trigger this method, but does not promise to wait for it to run over. The reason for this is that if an object is executed slowly in the Finalize () method, or a life cycle (more extreme), it is likely to cause other objects in the F-queue queue to be permanently waiting, or even to crash the entire memory-recycling system.

The Finalize () method is the last chance for an object to escape the fate of death, and later the GC will make a second small-scale mark on the object in F-queue, if the object is to successfully save itself in Finalize ()----just re-associate with any object on the reference chain. For example, assigning yourself to a class variable or a member variable of an object will remove the collection that is "about to be recycled" at the second token. If the object does not escape at this time, it is basically recycled.
The flowchart is as follows:

A demonstration of the self-salvation of one object

1 /**2 * This code demonstrates a two point3 * 1. Objects can save themselves while being GC4 * 2, this chance of self-help only once, because the Finalize () method of an object can only be called automatically once by the system. 5  */6  Public classFINALIZEESCAPEGC {7      Public StaticFINALIZEESCAPEGC Save_hook =NULL;8 9      Public voidisAlive () {TenSystem.out.println ("Yes, I am still Alive"); One     } A  -     protected voidFinalize ()throwsThrowable { -         Super. Finalize (); theSystem.out.println ("Finalize Method executed!"); -Finalizeescapegc.save_hook = This; -     } -  +      Public Static voidMain (string[] args)throwsinterruptedexception { -Save_hook =NewFINALIZEESCAPEGC (); +  A         //object for the first time to successfully save himself atSave_hook =NULL; - System.GC (); -  -         //because the Finalize method has a low priority, all pauses for 0.5 seconds to wait for it -Thread.Sleep (500); -         if(Save_hook! =NULL) { in save_hook.isalive (); -}Else { toSystem.out.println ("No, I am dead qaq!"); +         } -  the         //----------------------- *         //The above code is exactly the same as above, but this time the rescue failed!!!  $Save_hook =NULL;Panax Notoginseng System.GC (); -  the         //because the Finalize method has a low priority, all pauses for 0.5 seconds to wait for it +Thread.Sleep (500); A         if(Save_hook! =NULL) { the save_hook.isalive (); +}Else { -System.out.println ("No, I am dead qaq!"); $         } $     } -}

Run results

1 Finalize Method executed! 2  3 No, I am dead qaq!

As can be seen from the results, the Finalize () method of the Save_hook object was actually triggered by the GC collector and was successfully escaped before being collected.

Note: the Finalize () method of any object is called only once by the system, and if the object faces the next collection, its Finalize () method will not be executed again, so the second code's self-help action fails, and it is recommended that you try to avoid using it.

Resources:

1. "In-depth understanding of Java Virtual machines: JVM advanced features and best practices"

2. https://my.oschina.net/ydsakyclguozi/blog/404389

3. http://blog.csdn.net/ochangwen/article/details/51406779

Java Virtual machine Note (ii): GC garbage Collection

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.