<html>

Source: Internet
Author: User
Tags xms

Suppose you haven't seen your first friend. Please step: Java Memory Recycling (1)-Java garbage collection mechanism
 

No matter what garbage collection algorithm must be completed two things. First, it must detect the garbage object. Second, it must reclaim the heap space occupied by the garbage object and make it available again to the program.

Garbage detectors are typically implemented by defining a set of root references and calculating their achievable set of objects. An object, which is said to be accessible (reachable), if it can be visited by a running program through a reference path that begins with the root reference. to the program. Root references are always available.

An object is assumed to be accessible, it is called the active object. Otherwise, it is called garbage because it no longer has any effect on the future operation of the program.
The composition of the root reference set depends on the detailed implementation of the JVM, but it always contains references to the local and operand stacks in all stack frames, as well as references held in static variables.

Another source of the root reference is a constant pool, which may hold a reference to some strings in the heap, often the class name, parent class name, parent interface name, domain name, domain signature, method name, method signature, and so on. One possible source of root references is those that are passed to the local law (native method) but have not yet been released. Another potential source of the root reference is the runtime data area of the JVM, because some implementations place a portion of the JVM Runtime data area on the heap, such as the class data itself in the method area.
The set of accessible objects contains all the objects that can be visited directly or indirectly through the root reference. Technically, the set of objects is a transitive closure of the root reference set under the point-to-relationship.
The two basic ways to differentiate between active objects and garbage are reference counting and tracing. The standard garbage collector in the JDK all uses the tracking method, although the detailed form is different.
  

One, reference counting method (Reference counting Collector)

Reference counting is an early strategy for garbage collection. In such a method, each object in the heap has a reference count. When an object is created and points to its reference is assigned to a variable, the object's reference count is set to 1. The reference count of the object is incremented by 1 whenever its reference is assigned to a different variable.

When the variable that holds the reference to the object leaves its scope or is assigned a new value. The reference count of the object is reduced by 1.

Any object once its reference count becomes 0. It becomes rubbish.

Once an object is garbage collected, the reference count of all other objects it references must be decremented. Such Garbage collection of an object can cause a continuous garbage collection of other objects.


The advantage of this method is that. The reference counting collector algorithm is simple and suitable for incremental collection, which is especially suitable for the real-time environment where the program cannot be interrupted for a long time. Other than that. The collection process also helps to improve the locality of references.

The downside is that the reference count cannot detect an unreachable loop structure (two or more objects referencing each other). Because their reference count will never be 0.

Another disadvantage is that each increment or decrement of the reference count brings additional overhead. The algorithm also requires a high degree of coordination with the compiler. Because of these inherent flaws, the reference counting algorithm is rarely used in production environments.


 

Second, tracing algorithm (tracing Collector)

The trace collector starts from the root reference and explores and paints an object reference graph. Objects encountered during the exploration process are flagged in some way.

Typically, the tag can be stored either in the object itself or in a separate bitmap.

Objects that are not marked after the search are unreachable are objects that can be garbage collected.
The main tracking algorithm is called "Mark and Clean Up" (Mark and Sweep).

The name identifies two phases of the garbage collection process. In the tagging phase. The garbage collector walks through the reference tree and marks each encountered object. During the cleanup phase, unmarked objects are freed and the corresponding memory is returned for use. In the JVM, the cleanup phase must contain the end of the object (finalization).


The tag and cleanup algorithm is simple to implement and can easily recycle the loop structure. And there is no additional overhead and dependency on the compiler to maintain the reference count. But it also has shortcomings, the biggest problem is that in the clean-up phase, all the objects in the heap, whether or not accessible, will be interviewed.

On the one hand, this has a very negative performance impact on the virtual storage system on which a heap that is likely to have a page exchange depends; Because a very large part of the object may be garbage, it means that the garbage collector spends a lot of effort on checking and disposing of the garbage. No matter from which point of view. This algorithm can lead to the problem that the collection pause time is too long and the collection overhead is too large. Another disadvantage of marking and cleaning up the collector is that its easy causes fragmentation of the heap, which can cause problems with reference locality or large object allocation failures.
In the mainstream of commercial programming languages (Java, C #. Even the mainstream implementation, which includes the old Lisp mentioned earlier, is called the reachability analysis to determine whether an object survives. The basic idea of this algorithm is to use 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 (Reference Chain), when an object to the GC Roots is not connected to any reference chain (in the words of graph theory, that is, from the GC roots to the object unreachable), it proves that this object is not available. As seen in 3-1, objects 5, 6, and object 7 are not accessible to GC roots, although they are associated with each other, so they will be judged as recyclable objects.

In the Java language, objects that are available 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, the general native method) in the local method stack

Three, compacting algorithm (compacting Collector)

The JVM's garbage collector is likely to have a strategy against heap fragmentation.

The two strategies commonly used to mark and clean collectors are compression or copying.

Both of these methods reduce heap fragmentation by moving objects at high speed. The compression collector slides the active object across the spare memory area to one end of the heap, and in this process, one end of the heap becomes a large contiguous spare area.

All references to the moved object are also updated to point to the new location.
To better understand the compression process, the heap can be compared to a shelf. Some of them are filled with books of different thicknesses. Spare space is the gap between books. Compression is the passage of all books in one Direction to bridge the void.

It starts with the book closest to the partition. Push it to the bulkhead, then push the book near the bulkhead to the first book. The third book is then pushed to the second book, and so on. Finally, all the books at one end, all spare space at the end.


Reference updates for moved objects can be simplified by adding a layer of addresses to the object reference. Object references no longer point directly to objects in the heap. Instead, it points to a table item in the object's handle table, where the object handle directly points to the actual object in the heap.

Such When an object is moved, it is only necessary to update its handle in the object handle table, and any references to that object in the running program do not have to be updated. Such a method simplifies the work of eliminating heap fragmentation, but adds the overhead of every object access.


  

Iv. Copying algorithm (coping Collector)

The copy collector uses the same tracking technology, which moves all the active objects to a new area, and the original area becomes the spare space. Because the moved object is placed next to each other in the new area. Thus, the possible gaps between objects in the original area are also eliminated.

The copy of the object can be carried out instantly during the tracking process without having to mark and clean two separate stages to complete. When an object is copied to a new region in real time, its copy in the original area is replaced by a steering pointer (forwarding pointer) that points to the copy of the object in the new region. The steering pointer lets the garbage collector detect those references (the objects that they refer to have been moved to a new area) and update them with the values of the steering pointer so that they point to the object's new position.


A generic copy collector algorithm is known as "Stop and copy" (Stop and copy). In this method, the heap is divided into two regions, whenever only one of the areas is used.

Objects are allocated in the same region until all the space in the zone is exhausted.

At this point, the program run is aborted. The heap is traversed, and the activity objects encountered during the traversal are copied to the heap with an area. When the stop and copy process is complete, the program resumes running. The memory of the object will be allocated from this new area of the heap until it is exhausted. At that time the program will be stopped again. The heap is traversed. The active object is copied back to the original area. The cost of this scenario is that the required memory is twice times the specified heap space. Since only half of the memory is used at any one time.
The advantage of the Copy collection algorithm is that it only visits the active object. Garbage objects are not checked. Naturally, there is no need to be paged to memory or cached. The time it takes to collect the process depends only on the number of active objects. This avoids unnecessary collection overhead. It also minimizes the time to collect pauses. It's just that. In addition to the additional memory consumption, the copy collector also has to bear the cost added of object copy and reference updates. This is even more noticeable when there are more longevity objects, because they are copied back and forth each time they are collected.
  

V. Generation algorithm (generational Collector)

Through observation and experimentation, for most applications written in multiple languages, the objects they create have the following characteristics: 1) Most objects have very short lifetimes. But there are always some objects that live long enough; 2) older objects rarely refer to young objects. The above facts are also referred to as the "weak generation hypothesis" (weak generational hypothesis), which is the precondition and basis of the generational collection algorithm.
In such a method, the object is divided into groups according to age (generation), and the heap is divided into two or more sub-heaps, each of which serves a generation of objects, so the sub-heap is often called a generation. The most frequent garbage collection is carried out in the youngest generation.

Because most objects have very short life spans, only a very small part of the youngest object can survive the first collection.

Assuming that one of the youngest objects survives after a few garbage collections, it will be promoted to a higher-life generation (moved to a sub-heap).

Compared to younger generations. The frequency of garbage collection is always reduced relative to older generations.

As objects continue to mature in their current generation (through multiple garbage collection without dying), they are eventually moved to a more senior generation than their current generation.


The generational collection technique can be applied to the copy algorithm to solve the problem that it is inefficient in dealing with long-lived objects, and can also be applied to mark and clean up the algorithm. In either case, partitioning the heap into object generations helps to improve the efficiency of the most important garbage collection algorithms.


 

Vi. Adaptive Algorithm (Adaptive Collector)

The Adaptive collection algorithm exploits the fact that some collection algorithms work better in some cases, while others work better in other situations. The adaptive collector monitors the current state of the heap and adjusts its garbage collection techniques accordingly. It may only make adjustments to the parameters of a single collection algorithm at the same time that the program is running. It is also possible to switch from one algorithm to another, and perhaps even to divide the heap into sub-heaps and use different algorithms at the same time on different sub-heaps.
Use the adaptive method. The designer of the JVM implementation no longer has to choose a particular garbage collection technology. They are able to use multiple techniques to assign each algorithm the job that best suits it.


In fact, in modern JVM implementations, most garbage collection subsystems have some degree of adaptability, and very often we have to choose strategies and set goals to get comfortable results. Detailed collection algorithm selection and parameter configuration can be handled by the garbage collection subsystem itself. This is how the garbage disposal subsystem in Sun's hotspot JVM works, with detailed details that are time-specific.
References:
1) Cheney ' s algorithm
2) Garbage Collection-chapter 9 of Inside the Java Virtual machine
3) Java theory and practice:a Brief History of garbage collection

Read the full text of the copyright notice: This article is the original blogger article. Not reproduced without the consent of the blogger.

Report

    • Label:
    • Java /
    • q= garbage collection &t=blog "target=" _blank "> Garbage collection /

    • Algorithm /
    • This article has been included in the following column:
0Article comments
Related articles recommended
Java Foundation--memory management, garbage collection----------------------------------------------------------------------------------- -----------<p style= "Text-align:right
  • Tvmovie
  • 2010-03-04 13:50
  • 2524
Explore Java Virtual machine--memory management and garbage collection Quest Java Virtual machine--memory management and garbage collection This article is based on the garbage Collector (Bi Xuan) of the Sun JDK 1.6. Readers are asked to search the Web.

1. When the Java Virtual machine executes ...

  • Cqhweb
  • 2015-03-31 16:36
  • 304
Java Memory allocation principle and garbage collection article excerpt to: http://lz12366.iteye.com/blog/640147http://hi.baidu.com/hbeing/blog/item/ c708220220ac88034afb516c.htmlhttp://dev.yesky.com/178/2278678.shtml Java Program execution mechanism: The JVM is a stack-based virtual machine. <span
  • zl198751
  • 2010-12-21 17:44
  • 715
JVM memory segment allocation, Java garbage collection tuning. Heap settings, JVM memory recovery algorithm http://hi.baidu.com/kingtckingtc/blog/item/ca5606f4decd5767ddc4740b.html
  • jadar_ly
  • 2009-11-23 16:28
  • < I class= "icon Iconfont icon-yuedu" > 257
Quest Java Virtual Machine--memory management and garbage collection Quest Java Virtual machine--memory management and garbage collection 1, Data area 2 for Java Virtual machine execution, frequently used memory region tuning parameters-xms: initial heap size. 1/64 of physical Memory (<1GB). By default (Minheapfreeratio parameters can be adjusted) when the free heap memory is less than 40%, the JVM increases the heap until the maximum limit of-xmx-xmx: Maximum heap size, default (Maxheapfreeratio parameters can be adjusted) when the free heap memory is greater than 70%, The JVM will lower the heap until the minimum limit of-XMS-xmn: The size of the new generation of memory, note: The size here is (eden+ 2 survivor space). New Gen
  • joe_zhjiang
  • 2012-11-28 23:16
  • 543
Explore Java Virtual machines-memory management and garbage collection This article is based on the Sun JDK 1.6 garbage Collector (Bi Xuan) of the collation and summary, the original text readers on the internet search. 1, the Java Virtual machine when the data area 2, the memory area is often used to adjust the number of parameters-X ...
  • mn11201117
  • 2013-04-08 10:02
  • 608
Java Memory garbage collection mechanism one, memory allocation policy general memory coarse can be divided into
  • Rainyear
  • 2012-11-25 02:11
  • 48V
in-depth understanding of Java Virtual Machine notes--chapter III garbage Collector and memory allocation Policy Chapter 3.1 outlines what memory needs to be recycled? When do I recycle? How to recycle? Here the garbage collector focuses on the memory of the Java heap and the method area. Program counter, virtual stack, local method stack three regions will be born with the thread, with the thread, not ...
  • sinat_32487221
  • 2017-02-17 17:42< /li>
  • 852
Explore the Java Virtual machine-memory management and garbage collection

  • Grefr
  • 2014-06-16 23:29
  • 558
  • "Go" Java Memory management and garbage collection reprinted from: http://blog.csdn.net/sup_heaven/article/details/39157829 One, Java memory model Java Virtual Opportunity divides memory into several different management areas, these ...
    • qq_28385797
    • 2016-12-07 17:04
    • 165
    Android Developer. + Focus
    Original
    -
    Fans
    -
    Like
    0
      • a sentence to solve the matter why say three sentences, kotlin into the pit guide
      • Android Transparent/immersive status bar practice and source code analysis
      • Bacula Virtual machine configuration Error:no route to host
      • XMPP Protocol Workflow Specific explanation
    many other articles Online Courses
    "Live" machine learning & Data Mining 7 weeks training--Wei Chi

    Utm_source=blog7 "target=" _blank ">" Package "System integration project manager Smooth customs clearance--Xu Bong

    • folder
    • like to cancel like
    • Collection
    • share Weibo QQ
    Collection Assistant Bad news report

    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.