Java garbage collection mechanism

Source: Internet
Author: User
Tags java throws

1. Garbage Collection

Garbage collection is the core concept of Memory Management in Java programming. JVM memory management mechanism is called garbage collection mechanism.

An object is placed in the JVM heap memory after it is created. When this object is never referenced, it will be reclaimed by JVM In the heap memory. The created objects cannot be regenerated, and they cannot be released through program statements. That is, when an object cannot be reached (found) through the root set in the JVM runtime space, this object is called a spam object. The root set consists of static and local reference fields in the class. JVM indexes objects through the root set.

During Java application development, two types of memory managed by JVM are often used: heap memory and stack memory. In short, heap memory is mainly used to store objects and variables created or instantiated during running of a program. For example, an object created using the new keyword. Stack memory is used to store static or non-static methods in program code.

(1) heap memory

When the JVM is started in the heap, the objects stored in the heap memory can be automatically recycled by the JVM and cannot be recycled by other external means, that is to say, developers cannot recycle objects in heap memory by adding relevant code. The heap memory is usually divided into two areas: the new object area and the old object area.

New object region: it can be subdivided into three small areas: the Eden region, the From Region, and the To region. The Eden region is used to store newly created objects. It is like a stack where new objects are created, just as pointers pointing to the stack are growing, when the objects in the Eden region are full, the JVM system will perform a accessibility test. The main task is to detect which objects cannot be obtained from the root set, and these objects can be recycled by JVM, and copy all the activity objects From the Eden region To the To region. At this time, some objects will be in the status exchange, and some objects will be transferred From the To region To the From region, in this case, the From region has an object. The entire process of object migration above is controlled by JVM.

Old object region: objects in the old object region still have a long life cycle. Most JVM system spam objects are originated from short-lived objects. After a period of time, objects transferred to the old object area become spam objects. At this time, they are all marked accordingly, and the JVM system will automatically recycle these junk objects. We recommend that you do not force the system to perform garbage collection frequently because the JVM will use limited system resources, the garbage collection process is prioritized, so that the application cannot quickly respond to requests from the user end. This will affect the overall system performance.

(2) stack memory

Heap memory is mainly used to store objects and variables created or instantiated during runtime. For example, an object created using the new keyword. Stack memory is used to store static or non-static methods in program code.

2. Object lifecycle in JVM

In the JVM runtime space, the entire lifecycle of an object can be roughly divided into seven stages:
Creation phase;
Application phase;
Invisible stage;
Inaccessible phase;
Collection phase;
Final stage;
Release Phase

The above seven stages constitute the complete lifecycle of the objects in the JVM.


(1) Creation stage

In the object creation stage, the system completes the object creation process through the following steps:

<1> allocate storage space for objects;
<2> start constructing objects;
<3> initialize static members from superclass to subclasses;
<4> superclass member variables are initialized in sequence and the constructor of superclasses is called recursively;
<5> subclass member variables are initialized in sequence and called by subclass constructor.

When creating an object, pay attention to several key application rules:

<1> avoid creating an object in the loop body, even if the object occupies little memory space.
<2> try to make the object comply with the garbage collection standard in a timely manner. For example, myObject = null.
<3> do not use a deep inheritance level.
<4> accessing local variables is better than accessing variables in the variables class.
(2) Application phase

In the object reference phase, the object has the following features:

<1> the system maintains at least one Strong Reference of the object );
<2> All references to this object are strongly referenced (unless we explicitly use Soft Reference and Weak Reference) or Virtual Reference (Phantom Reference )).

Strong Reference: indicates that the JVM Memory Manager traverses all the paths in the heap to reach the object starting from the root Reference set. When any path to an object does not contain referenced objects, the reference of this object is called a strong reference.

Soft Reference: Soft Reference is mainly characterized by a strong Reference function. This type of memory is recycled only when the memory is insufficient. Therefore, when the memory is sufficient, it is usually not recycled. In addition, these referenced objects can be set to null before Java throws an OutOfMemory exception. It can be used to implement Cache of some common resources and implement the Cache function to ensure maximum use of memory without causing OutOfMemory.

?
The following is the implementation code of soft reference:
Import java. lang. ref. SoftReference;
...

A a = new ();
...
// Use
...

// When a is used up, set it to soft reference type and release strong reference.
SoftReference sr = new SoftReference ();
A = null;
...
// Next time
If (sr! = Null ){
A = sr. get ();
} Else {
// GC due to low memory, a has been released, so it needs to be reloaded
A = new ();
Sr = new SoftReference ();
}
The introduction of soft reference technology enables Java applications to better manage memory, stabilize the system, prevent system memory overflow, and avoid system crashes. Therefore, this technology should be used whenever possible to process objects that occupy a large amount of memory and have a long life cycle. Improve system stability.


Weak Reference: The biggest difference between a Weak application object and a Soft Reference object is that GC needs to use algorithms to check whether Soft application objects are recycled during garbage collection, for Weak references, GC is always recycled. The Weak reference object is easier and faster to be recycled by GC. Weak reference objects are often used in Map structures.

?
Import java. lang. ref. WeakReference;
4 ....
5.
6. A a = new ();
7 ....
8.
9. // use
10 ....
11.
12. // when a is used up, set it to Weak reference type and release strong references.
13. WeakReference wr = new WeakReference ();
14. a = null;
15 ....
16.
17. // The next time
18. if (wr! = Null ){
19. a = wr. get ();
20.} else {
21. a = new ();
22. wr = new WeakReference ();
23 .}
Phantom Reference: Virtual references are rarely used to assist in the use of finalize functions.

A Phantom Reference object refers to an object that is not reachable but has not been recycled by GC after the finalize function is executed. This type of object can assist finalize in some subsequent recycling work. We can enhance the flexibility of the Resource Recycling mechanism by covering the clear () method of Refernce.


In actual program design, weak references and virtual references are rarely used. There are many cases where soft references are used, because soft references can accelerate JVM's garbage memory collection speed, it can maintain system operation security and prevent problems such as memory overflow (OutOfMemory.


(3) invisible stage
When an object is in an invisible stage, it means that we cannot reference it in code in other regions, and its strong reference has disappeared. For example, if the local variable exceeds its visibility
.

?
1. try {
2. Object localObj = new Object ();
3. localObj. doSomething ();
4.} catch (Exception e ){
5. e. printStackTrace ();
6 .}
7.
8. if (true ){
9. // The localObj object in this region is invisible and the compiler reports an error.
10. localObj. doSomething ();
11 .}
(4) Inaccessibility
Objects in the inaccessibility phase cannot be directly or indirectly strongly referenced in the VM's object reference root set. These objects are generally temporary variables in all thread stacks. All static variables that have been loaded or references to local code interfaces.


(5) Collection, termination, and release phases
When an object is in the collection, termination, and release phases, there are three situations for this object:

<1> the recycler finds that the object is no longer reachable.

<2> the finalize method has been executed.

<3> the object space has been reused.

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.