3. Garbage collector and garbage collection algorithm

Source: Internet
Author: User
Tags java reference

1. Overview

In the various parts of the Java Memory Runtime area:

The program counter, virtual machine stack, local method stack 3 each area with the thread, with the thread. The stack frame in the stack methodically executes the stack and stack operations as the method enters and exits. How much memory is allocated per stack frame is basically known as the class structure, so memory allocation and recycling in these areas are deterministic and do not require much consideration.

The heap is not the same as the method area, and you should know what objects are created only when the program is running, and this part of memory allocation and recycling is dynamic and therefore the main concern.

2. Object death Discrimination 1. Reference counting method

Add a reference counter to the object, and whenever there is a place reference, the value of the counter is incremented by 1, and when the reference fails, the counter value is reduced by 1, and any object with a counter value of 0 at any time is the object that will no longer be used. The implementation is simple and efficient, but it is difficult to solve the problem of mutual circular referencing between objects. As a result, mainstream Java virtual machines do not manage memory in this way.

2. Accessibility analysis

The mainstream realization is the accessibility analysis. The basic idea is to search through a series of objects called "GC Roots" as the starting point, searching through the path called the reference chain (Reference Chain), and proving that the object is not available when an object is connected to the GC Roots without any reference chain.

The objects that can be used as GC roots include the following:

    1. The object referenced in the virtual machine stack (local variable table in the stack frame);

2. Objects referenced by static properties in the method area;

3. Methods to go to the target of the midfield;

4. The object referenced in the local method stack (that is, the generally referred to as the native method).

      Cause: The primary area of GC management is the Java heap, which is typically garbage collected only for heaps. The method area, stack, and local method areas are not managed by the GC, so the objects in these areas are selected as GC roots, and the objects referenced by GC roots are not recycled by GC.

    If you want to refine GC ROOTS,GC Roots include:

      1, all aged with objects

2, all global objects
3, all JNI handles
4, all Locked objects
Objects held by 5,JVMTI
6, Code snippet Code_cache
7, all ClassLoader, and its loaded class
8, all dictionaries
9,flat_profiler and Management
10, most importantly, all of the reference type variables running on the thread stack. 3. Referring to either the reference count or the accessibility analysis, all talk about "references", JDK1.2 before the Java reference: if the value stored in the reference type of data represents the money of another piece of memory, it becomes the memory that represents a reference. So after JDK1.2,The reference is divided into: strong reference, soft reference, weak reference, virtual reference 4 kinds. Strong reference (Strong Reference): As long as a strong reference exists, the garbage collector never reclaims the referenced object, such as Object obj = new Object (), soft reference (Soft Reference): Describes some useful but not necessary objects, When a memory overflow is about to occur, the JDK provides softreference to implement soft references, weak references (Weak Reference): Used to describe non-essential objects, weaker than soft references, objects associated with weak references can only survive until the next garbage collection occurs. Garbage collection occurs, regardless of whether the memory is sufficient to be recycled, the JDK provides weakreference to implement soft reference, virtual reference (Phantom Reference): Also become a phantom reference or phantom Reference, the weakest reference relationship. Whether an object has a virtual reference does not affect its lifetime at all, nor can it pass through a virtual reference to an object instance, the only thing that can be consumed by the object community is the ability to receive a system notification when the object is reclaimed by the collector. The JDK provides a phantomreference class to implement soft references; 4. Surviving deathto announce the death of an object at least two times to mark the process:If there is no reference chain connected to GC roots through accessibility analysis, it is first tagged and filtered. The filter condition is whether this object has an execute 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 an object is required to execute the Finalize () method, it will be placed in the F-queue queue and executed later by a low-priority finalizer thread created by the virtual machine itself, which will trigger this method, but not wait for it to execute. Otherwise, if an object executes slowly in the Finalize () method, the memory recycling system crashes. The Finalize () method is the last time an object escapes the chance of death. Later, the GC will make a second small-scale mark on the objects in the F-queue, and if the object does not save itself before the second tag, it is recycled.  The way to save is to associate with any object on the reference chain. Example code:
 Public classFINALIZEESCAPEGC { Public StaticFINALIZEESCAPEGC Save_hook =NULL;  Public voidisAlive () {System.out.println ("Yes,i am Steal alive!"); }        protected voidFinalize ()throwsthrowable{Super. Finalize (); System.out.println ("Finalize method executed."); Finalizeescapegc.save_hook= This; }         Public Static voidMain (string[] args)throwsinterruptedexception{Save_hook=NewFINALIZEESCAPEGC (); //object for the first time to successfully save himselfSave_hook =NULL;        System.GC (); //because the finalize priority is low, 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 it failed to save itself.Save_hook =NULL;        System.GC (); //because the finalize priority is low, 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

Operation Result:

Finalize Method Executed.yes,i am steal Alive! No, I am dead.

Because the Finalize method of an object is only automatically called once by the system, its finalize () method will not be executed again if it is faced with the next collection, only to be recycled. Because the Finalize () method is expensive and uncertain, it is not possible to guarantee the order of calls for individual objects, so do not use.

5. Recovery method Area

Although the garbage collection efficiency of the permanent generation is very low, but also will be recycled, the main two parts: waste constant oh useless class.

Recycling of obsolete constants is similar to the objects in the heap, and it is also a reference.

Recycling of useless classes needs to meet the following 3 conditions:

1. All instances of this class have been recycled, i.e. no instances of the class exist in the Java heap;

2. The classloader that loaded the class has been recycled;

3. The corresponding Java.lang.Class object of this class is not referenced anywhere, and any instance of the class cannot be accessed anywhere through reflection.

Even if the condition can only be recycled, it is not as if the object will be recycled, and whether the virtual machine has its own parameter control over the class being recycled.

    Scenarios in which frequent custom classloader such as the use of reflection, dynamic proxies, cglib, bytecode frameworks, dynamically generated JSPs, and OSGi will require the ability of the virtual machine to unload classes automatically to ensure that the permanent generation does not overflow.

3. Garbage collector and garbage collection algorithm

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.