Garbage collector and memory allocation policy

Source: Internet
Author: User
Tags throwable

  The dynamic allocation of memory and the memory recycling technology are already quite mature, everything seems to be in the "Automation" era, then why do we have to understand the GC and memory allocation? The answer is simple: when you need to troubleshoot various memory overflows, memory leaks, and when garbage collection becomes a bottleneck for the system to reach higher concurrency, we need to implement the necessary monitoring and tuning of these "automated" technologies.
Object is dead
The heap holds all of Java's object instances, and the first thing the garbage collector can do before it recycles the heap is to determine which of these objects are "alive" and which have been "dead."
  Reference Counting Algorithm : Add a reference counter to the object, and whenever there is a place to reference it, the counter value is incremented by 1, and when the reference fails, the counter value is reduced by 1, and any object with a counter of 0 at any time is impossible to be used again.
For a simple example, look at the TESTGC () method in Listing 3-1: Objects Obja and OBJB have field instance, assignment makes obja.instance = objb and objb.instance = Obja, and beyond that, These two objects have no reference, 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 tell the GC collector to reclaim them.

    /*** After the TESTGC () method is executed, will obja and OBJB be GC? * @authorZzm*/       Public classREFERENCECOUNTINGGC { PublicObject instance =NULL; Private Static Final int_1MB = 1024 * 1024; /*** 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];  Public Static voidTESTGC () {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 (); }      } 
View Code

Operation Result:

 [Full GC (System) [tenured:0k->secs] 4603k->>0.0150007 secs] [times: =.01 =.00, =.02 secs] [ 0x00000000055e0000, 0x0000000005fe0000, 0x0000000005fe00000x00000000055f4850, 0x0000000005de0000)  0x0000000005de0000, 0x0000000005ee0000)  0x0000000005ee0000, 0x0000000005fe0000) [ 0x0000000005fe0000, 0x00000000069e0000, 0x00000000069e0000 0x00 00000006014a18, 0x0000000006014c00, 0x00000000069e0000) [ 0x00000000069e0000, 0x0000000007ea0000, 0x000000000bde0000)  0x0000000006cd2398, 0x0000000006cd2400, 0x0000000007ea0000) No GKFX spaces configured. 
View Code

It is clear from the running results that the GC log contains "4603k->210k", which means that the virtual machine does not reclaim them because the two objects are referencing each other, which also indicates from the side that the virtual machine does not determine whether the object survives by reference counting algorithms.
  Accessibility Analysis algorithm: The basic idea is to use a series of objects called "GC Roots" as the starting point, starting from these nodes to search down, search through the path called the reference chain (Reference Chain), when an object to the GC Roots no reference chain is connected (in the case of graph theory, from GC roots to the object unreachable), it proves that this object is not available. As shown in 3-1, 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.


reference
in JDK After 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, These four reference intensities gradually weaken in turn.

  Objects that are unreachable in the root search algorithm are not "dead", and they are temporarily in the "probation" stage to actually declare an object to die, at least two times to go through the tagging process: If the object finds no reference chain connected to the GC roots after the root search, Then it will be marked for the first time and filtered to see if it is necessary for this object to execute the 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 treats both cases as "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 queue named F-queue, and then executed by a low-priority finalizer thread that is automatically created by the virtual machine at a later time. 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 executes slowly in the Finalize () method, or if a dead loop (more extreme) occurs, 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 the 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 (the This keyword) to a class variable or a member variable of an object, it will be removed from the collection that is "about to be recycled" at the second mark, and if the object has not escaped at this time, it is really not far from dead. From code listing 3-2 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 automatically *@authorZzm*/       Public classFINALIZEESCAPEGC { Public StaticFINALIZEESCAPEGC Save_hook =NULL;  Public voidisAlive () {System.out.println ("Yes, I am still alive:)"); } @Overrideprotected voidFinalize ()throwsThrowable {Super. Finalize (); System.out.println ("Finalize Mehtod executed!"); Finalizeescapegc.save_hook= This; }            Public Static voidMain (string[] args)throwsThrowable {Save_hook=NewFINALIZEESCAPEGC (); //object for the first time to successfully save himselfSave_hook =NULL;           System.GC (); //because the finalizer method has a low priority, pause for 0.5 seconds to wait for itThread.Sleep (500); if(Save_hook! =NULL) {save_hook.isalive (); } Else{System.out.println ("No, I am dead:("); }//The following code 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 (500); if(Save_hook! =NULL) {save_hook.isalive (); } Else{System.out.println ("No, I am dead:("); }      }      } 
View Code
    Finalize Mehtod executed!       Yes, I am still alive:)      
View Code

  As you can see from the running results of code listing 3-2, the Finalize () method of the Save_hook object was actually triggered by the GC collector and escaped successfully before being collected.
Collection Method Area
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.
Classes need to meet the following 3 conditions to be considered "useless classes":

    • All instances of the class have been reclaimed, i.e. 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 used to access the class's methods at any place.
garbage Collection Algorithmtag-purge algorithm

 The algorithm is divided into "mark" and "clear" two stages: first mark out all the objects that need to be recycled, after the mark is complete, all the tagged objects are collected uniformly. Its main shortcomings are two: one is the efficiency problem, the labeling and removal process is not efficient, and the other is a space problem, the mark after the purge will produce a large number of discontinuous memory fragmentation, too much space debris may cause, When the program needs to allocate large objects in the future, it cannot find enough contiguous memory and has to trigger another garbage collection action in advance.

Replication Algorithms

  It divides the available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is exhausted, copy the surviving object to the other piece, and then clean up the used memory space once. This makes each one of the pieces of memory recycling, memory allocation will not consider the complexity of memory fragmentation, as long as the mobile heap top pointer, in order to allocate memory, simple implementation, efficient operation. But the cost of this algorithm is to reduce the memory to half of the original, it is a little too high.

tagging-sorting algorithms

 According to the characteristics of the old age, someone proposed another "mark-and-sweep" (mark-compact) algorithm, the marking process is still the same as the "tag-purge" algorithm, but the next step is not directly to the recyclable objects to clean up, but to let all the surviving objects moved to one end, Then directly clean out the memory outside the end boundary, as shown in 3-4 of the "mark-sweep" algorithm

Generational collection Algorithms

 The current garbage collection of commercial virtual machines uses the "generational collection" (generational Collection) algorithm. The Java heap is generally divided into the new generation and the old age, so that according to the characteristics of each era to adopt the most appropriate collection algorithm. In the Cenozoic, every garbage collection is found to have a large number of objects died, only a small number of survival, then choose the replication algorithm, only need to pay a small number of surviving objects of the replication cost can be completed collection. In the old age, because of the high survival rate of the object and the lack of additional space to guarantee it, it must be recycled using the "mark-clean" or "mark-sweep" algorithm.

Garbage collector and memory allocation policy

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.