Garbage collector and memory allocation policy (in-depth understanding of Java virtual machines)

Source: Internet
Author: User
Tags garbage collection

3.1 Overview What problems does the garbage collector solve?
    • Which memory needs to be recycled
    • When is it recycled?
    • How to Recycle
Reference counting algorithm:When there is a reference to a place, +1, the reference fails,-1. Disadvantage: The problem of circular referencing between objects.Accessibility Analysis algorithm:Idea: Through a series of objects that become "GC Roots" as starting points, starting from these nodes to explore, searching through the path becomes the reference chain (Reference Chain), when an object to the GC Roots no reference chain connected, it is difficult to revolution this object is not available.Javain LanguageGC Rootsobjects include the following:1.objects referenced in the virtual machine stack (local variable table in the stack frame)2. Objects referenced by class static properties in the method area3. Objects referenced by constants in the method area4.Local Method StackJNI(Nativemethod) refers to the object2.References  Strong Referencesis common in program code, likeObject obj = new Object ()This type of reference, as long as a strong reference exists, the garbage collector will never reclaim the referenced object  Soft Referencesused to describe elements that are useful but not necessary. Before the system will have a memory overflow exception, these objects are listed in the Reclaim scope for a second recycle, and if the collection does not have enough memory to throw a memory overflow exception  Weak referencesused to describe a non-mandatory object, but its strength is weaker than a soft reference, the object being referenced only survives until the next garbage collection occurs, and when the garbage collector is working, the object associated with the weak reference is reclaimed regardless of whether the current memory is sufficient  Virtual ReferenceThe only purpose is to be able to receive a system notification when the object is reclaimed by the collector. Finalize method 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.    FInalize () is the protected method of object, which can be overridden by subclasses to implement resource cleanup efforts. Recycling Method AreaObsolete constants and useless classes, such as String "ABC".   class to reclaim the conditions that are met: 1. All instances of this class have been reclaimed and no instances exist in the Java heap.  2. The class loader that loaded it has been recycled. 3.The Java.lang.Class object used by this class is not referenced anywhere, and it is no longer possible to access the class's methods by reflection anywhere else3.3 garbage Collection algorithm1.tag-purge algorithm: All objects that need to be reclaimed are marked first, and all tagged objects are collected uniformly after the tag is complete. deficiencies: Efficiency issues, space problems (resulting in massive fragmentation). 2. Copying Algorithms divide available memory by capacity into two blocks of equal size, using only one piece at a time. When this memory is used up, copy the surviving object to the other piece, and then clean out the used memory space once. This makes every time the entire half of the memory collection, memory allocation will not consider the complexity of memory fragmentation, as long as moving the heap top pointer, sequentially allocated memory. Insufficient: Reduce the memory to half the original. in fact, divide the memory into a larger Eden space and survivor space, using Eden and another survivor each time. hotspot Virtual Machine default eden:survivor=8:1. The available memory space in the Cenozoic is 90% of the total cenozoic capacity. 3. Labeling-sorting algorithm tag, let all surviving objects move to a segment, and then directly clean out the memory outside the end boundary. 4. Generation of collection AlgorithmsThe Java heap is divided into the new generation and the old age, can be based on the characteristics of the various eras to adopt appropriate algorithms. implementation of 3.4HotSpot algorithmWhen the GC is in progress, all execution threads must be paused,Stop the WorldSafety PointWhen the program executes, it does not stop at all places to execute the GC, only to reach the security point to pause. (archive point). Active Interrupt: Sets a flag that each thread executes when it actively polls for this flag and discovers that the interrupt flag is true on its own suspension.

Security Zone:3.5 garbage collector

1.Serial Collector:Single ThreadCollectors, usingReplication Algorithms: When garbage collection is in progress, all other worker threads must be paused until the end of the collection. Simple and efficient, 2.ParNew collector: Serial collectorMultithreadingversion, you can work with the CMS collector. Use:-XX:+USEPARNEWGC to force the designation. 3.Parallel scavenge (clear dirt, sweep) is aThroughput PriorityProcessor features: The focus of the CMS collector is to shorten the thread when the user pauses when the spam phone is as short as possible, while his goal:achieve a controllable throughput. Control throughput Time-xx:maxgcpausemillis set throughput size:-xx:gctimeratio parameter.Throughput:Run user code time/(run user code time + junk phone time) The GC pause time is shortened in exchange for throughput and Cenozoic space. 4.Serial old collector, single-thread collector, usingMark-OrganizeAlgorithm. 5.Parallel Old Collectormulti-threading, tagging-groomingAlgorithm. 6.CMS collector (Concurrent Mark Sweep) to obtain the shortest payback time for the target collector, step: initial mark (single thread)-- ConcurrencyMark--Re-mark (single thread)-- ConcurrencyClear

The token is re-tagged to fix the tag record of the part of the object that caused the tag to change during the concurrent tag because the user program continues to run. Disadvantages
    • The CMS collector is very sensitive to CPU resources. The number of recycle threads that are started by default (number of CPUs +3) is/4,cpu in cases where the impact on the user program can become large.
    • Unable to handle floating garbage, a failure may occur that causes another full GC to be generated. Because the CMS concurrent cleanup phase of the user thread is still running, along with the program run naturally there will be new garbage generation, this part of the garbage appears after the tagging process, the CMS can not be processed in the secondary collection, they have to wait for the next GC to clean up.
It is therefore necessary to reserve a portion of the space to provide concurrent collection of programs for operational use.
    • Based on the tag-purge implementation, it creates a lot of memory fragmentation, which causes trouble for large object allocation.
7.G1 Collector Features:
    • Concurrency and parallelism
    • Collection of generations
    • Spatial integration: Based on the overall labeling-sorting algorithm. Local replication -based algorithm
    • Predictable pauses
G1 can be planned to avoid full-area garbage collection throughout the Java heap. G1 tracks the value of garbage accumulation in each region, maintains a prioritized list in the background, and prioritizes the most valuable region (Gabarage first--) Each time it is allowed to recycle. G1Origin). The operation of the remembered set is not computed, and the operation of the G1 collector is broadly divided into several steps: 1. Initial tag 2. Concurrency token 3. Final tag 4. Filter garbage collector parameters: Survivorratio: The ratio of Eden to survivor region capacity in the Cenozoic, Default 8. That is, both 8:1. 3.6 Memory allocation policy and recycling policyThe memory allocation of an object is allocated on the heap, and the object is allocated primarily in the new generation of Eden, and if Tlab is started, it will be allocated on Tlab by thread precedence. may also be allocated directly in the old age.
    • object Precedence in Eden allocation when the Eden Zone does not have enough space to allocate, the virtual machine will initiate a minor GC
    • large objects directly into the old age: such as strings and arrays
    • long-lived objects will enter the old age the virtual machine defines an object age counter for each object. If the object survives in Eden and is still alive after the first minor GC and can be accommodated by survivor, it will move to survivor space. Object in survivor each time a minor GC is added, the age increases by one year, and when the age increases, it will enter the old age.
    • Dynamic Object Age judgment if the sum of the objects of the same age in the survivor space is half the size of the >survivor space, then these objects go directly into the old age and need to wait for the ages to enter.
    • space allocation guarantee before the minor GC occurs, the virtual opportunity checks whether the largest available contiguous space in the old age is greater than the total space of all new generation objects, and if this condition is true, then the minor GC can ensure that it is safe. If not, the virtual opportunity to see if the Handlepromotionfailure setting value allows the warranty to fail. If allowed then continue to check whether the largest available continuous space in the old age is greater than the average size of the promoted to the old age object, if greater than, will attempt to minor GC once, although this MINORGC is risky: if it is less than, or the Handlepromotionfailure setting does not allow the risk, then the full GC is also changed to
 

Garbage collector and memory allocation policy (in-depth understanding of Java virtual machines)

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.