Java garbage collection mechanism

Source: Internet
Author: User
Tags object object

I. Overview

Previous article The Java memory model mentions that the memory managed by a virtual machine consists mainly of the following areas: program counters, virtual machine stacks, local method stacks, method areas, and heaps. The first three regions are life and death with threads, and the memory allocation and recycling of these areas is deterministic. The heap and the method area are nondeterministic, and only the program is running to know which objects are created, this article mainly discusses the two partial memory recycling.

Second, Java memory management

The memory management of Java is the allocation and release of objects. In Java, the use of the keyword new to request memory space for each object (except the base type), all objects are allocated space in the heap, and the release of the object is determined and executed by the GC (Gabage Collection). This mechanism simplifies the programmer's work while also aggravating the load of the virtual machine, which is one of the reasons why the Java program is running slower.

We can consider the object as a vertex of the directed graph, consider the reference relationship as a directed edge of the graph, have a pointing edge from the referrer to the cited object, and each thread object can be used as the starting vertex of a graph, for example, most programs start from the main process, and the graph is a root tree that starts with the main process vertex. In this graph, the root node is a valid object, the GC will not reclaim these objects, if an object and this root node is not accessible, then we think that this object is no longer referenced, can be recycled by GC. eg

class demo{    publicstaticvoid  main (string[] args)    {        Object O1= New Object ();                Object O2=new  object ();                O2=O1;    }}

Iii. What is a memory leak

In Java, the memory leak is the existence of some assigned objects, these objects have the following two characteristics, first of all, these objects are accessible, that is, in the graph, the existence of the path can be connected to it, and secondly, these objects are useless, that is, the program will no longer use these objects. If the object satisfies both conditions, these objects can be judged as a memory leak in Java, which is not reclaimed by the GC, but it consumes memory. The following is an example of a memory leak:

Vector v=new vector (ten);  for (int i=1;i<100; i++)   {      object o=new  object ();      V.add (o);      o=null;       }

We iterate over the object object and put the requested objects into a vector, and if we just release the reference itself, then the vector still references the object, so the object is not recyclable to the GC. Therefore, if the object has to be removed from the vector after it has been added to the vector, the simplest way is to set the vector object to null.

Common memory leak tools include tools including Optimizeit Profiler,jprobe Profiler,jinsight, Rational company Purify, etc.

Iv. garbage collection mechanism 1, the judgment standard of rubbish

  Reference Counting Method : Add a reference counter to an object, each time a place references 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 .

The mainstream Java Virtual machine does not use the above method to manage memory, mainly because it is difficult to solve the problem of cross-referencing between objects.

A simple circular reference problem is described as follows: There is object A and object B, object A contains a reference to object B, and object B contains a reference to object A. At this point, the reference counters for object A and object B are not 0. However, there is no 3rd object in the system that references a or B. That is, a and B are garbage objects that should be recycled, but because of the mutual reference between the garbage objects, which makes the garbage collector unrecognized, causing a memory leak.

classreferencecountinggc{ PublicObject instance=NULL;  Public Static voidTESTGC () {REFERENCECOUNTINGGC Obja=NewREFERENCECOUNTINGGC (); REFERENCECOUNTINGGC OBJB=NewREFERENCECOUNTINGGC (); Obja.instance=OBJB; Objb.instance=Obja; Obja=NULL; OBJB=NULL; }}

  Accessibility Analysis : Mainstream commercial languages use accessibility analysis algorithms to determine whether an object survives. The basic idea 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 "chain of Reference", when an object to the GC Roots no reference chain connected (that is, the GC Roots to this object is not reached), proves that this object is not available .

In Java, the objects that can be used as GC roots include:

    • The object referenced in the virtual machine stack;
    • Object referenced by class static property in method area
    • Objects referenced by constants in the method area
    • Objects in the local method stack that are referenced by JNI

To truly declare an object to die, at least two times to mark the process: If an object is found to have no reference chain connected to the GC roots after the accessibility analysis, it will be first marked and filtered for the first time by whether this object is necessary 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 is considered unnecessary) and if the object is judged to be necessary to execute the Finalize () method, The object is then placed in a queue called F-dequeu and later executed by a low-priority thread. The Finalize () method is the last chance for an object to escape the fate of death, and later the GC will mark the objects in the F-dequeu for a second time.

2. Garbage collection algorithm

  tag-purge algorithm : The algorithm is divided into two phases, mark and clear, first mark all the objects that need to be recycled, and collect all the tagged objects uniformly after the mark is complete.

There are two problems with this algorithm, one is inefficient and the other is the space problem, which causes a large number of discontinuous memory fragments after the mark is cleared, resulting in the inability to find enough contiguous memory during the program's running.

  Replication Algorithm : This algorithm divides the available memory into two blocks of equal size, using only one block at a time, and when this piece of memory is used up, copies the surviving objects to the other, then cleans up the used memory space once.

Java's new generation of serial garbage collector uses the idea of a copy algorithm. The Cenozoic is divided into 3 parts of Eden space, from space, to space. The From space and to space can be considered as two blocks of the same size, equal status, and can be used for character interchange. The From and to spaces are also known as Survivor Spaces, which are survivor spaces that are used to store objects that have not been reclaimed.

During garbage collection, the surviving objects in the Eden space are copied into unused survivor space (assuming to), and young objects in the survivor space being used (assuming from) are also copied into the to space (large objects, or older objects that go directly into the old age band, such as When the fruit to space is full, the object will go straight into the old age. At this point, the remaining objects in the Eden space and from space are garbage objects, which can be emptied directly, and the to space will hold the surviving objects after this collection. This improved replication algorithm not only guarantees the continuity of space, but also avoids a lot of wasted memory space.

  tag-Grooming algorithm : The tagging process, like the tag-purge algorithm, is followed by moving all surviving objects to one end and then directly cleaning out the memory outside the end boundary.

  Generational collection algorithm : According to the different life cycle of the object divided into several pieces of memory, is generally divided into the new generation and the old age, so that according to the characteristics of each era using the collection algorithm, in the new generation every garbage found a large number of objects died, the use of replication algorithm, The collection can be done with only a small amount of replication costs for the surviving objects.

Reference Documents :

1, in-depth understanding of Java Virtual Machine, Zhou Zhiming, Machinery Industry Press

2, https://www.ibm.com/developerworks/cn/java/j-lo-JVMGarbageCollection/

  

Java garbage collection mechanism

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.