Java Virtual Machine (4) -GC overview of how to recycle objects


1. Garbage Collection Overview

Along with running the program, the object program generated will more and more, while the memory system is limited, so the object is not cleared by the program is the key to long-term stable operation.

Garbage collection focuses on three issues

  • What object should be recycled?
    Of course, the object is of no use when the object is no longer referenced, we believe that the object should be recovered. How to determine whether the object is still quoted, will be described in detail later.

  • Objects should be recycled at what time?
    Program during operation, the object is referenced relationship has changed, how to choose the right time to start GC, it is also an important issue, described in detail later.

  • What should be recovered?
    When we know are useless after the object, how to remove unwanted objects, keep useful objects, garbage collection algorithm would be a matter of major concern, will be detailed in the next section.


2. Determine if an object is referenced

There are two ways to determine whether the object is referenced.

  • Reference counter method
    name implies, a counter is defined for each object, each time the object is referenced by a program counter + 1, when a reference is destroyed, the counter -1, 0 if the counter value, the object is useless.
    This method one drawback is that reference each problem can not be resolved between the objects.
    such as: objA.instance = objB; objB.instance = objA ;
    then the two objects will never be able to recover.

  • Reachability analysis
    to select a number of the root node (GC Roots) objects, reference is downwardly lookup, to find the path through the chain of references is called, if an object does not reference a strand can reach it, then it is unnecessary objects. As As shown in FIG.

The GCRoot A reference to an object.
A reference to the object B to the object.
Then A, B can not recover the object.


3. Select the appropriate time to start GC

  1. Because the program is running, a reference relation object has been changing, so we need to wait for all threads to stop execution (stop the world) to begin.

  1. Before preparing JVM GC, will be a flag is set to true, each thread to check this flag, if found to be true, stop executing down, and in reference to the current thread stack (local variables) of the object as GC Roots, look down the chain of references, and stored in a oopMap.

Note: which objects can be used as GC Roots?

  • Static variables
  • constant
  • Thread stack references (local variables) referenced objects

  1. If you execute one instruction per thread went to check the flag, clearly too wasteful, then let go a few steps to thread some locations before starting reachability analysis, these locations is called a safe point.

Note: As a safety position which generally point?

  • After the method return
  • After a single cycle end
  • Abnormal ready to jump before the catch.

  1. When the thread is sleep (), a reference relationship will not change, this time called security zone. Thread enters a secure area and went to the safe point effect is the same. When the thread sleep () end, will first pass flag to determine whether the end of the GC, not end it will continue to wait.

4. Other

  • When the object is not up, how to avoid being recycled?
    After implement finalize (), and only one execution finalize () to reclaim the opportunity to escape, but generally not recommended.
public class FinalizeEscapeGC {
    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive() {
        System.out.println("对象仍然活着!!!");
    }

    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize()方法被执行!!!");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

    public static void main(String[] args) throws Throwable {
        new FinalizeEscapeGC(); // 对象被创建
        SAVE_HOOK = null;
        System.gc(); // 回收,会执行finalize()
        Thread.sleep(500);

        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("对象已死!!!");
        }

        SAVE_HOOK = null;
        System.gc(); // 回收,finalize()已经被执行过,不会再被执行
        Thread.sleep(500);

        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("对象已死!!!");
        }
    }
}
finalize()方法被执行!!!
对象仍然活着!!!
对象已死!!!

  • About reference
    If the reference type is the data stored in the other memory address, the object reference time as a reference.
    According to the degree of strength, can be divided into strong references cited, soft, weak, reference phantom reference.

1. strong references

Object obj = new Object();  

Unless empty stack frame, strong references will not be GC, even in the event OOM.

2. Soft references

Object obj = new Object();
SoftReference<Object> sf = new SoftReference<Object>(obj);
obj = null;
sf.get();//有时候会返回null

Soft references will be recycled when out of memory occurs, how get through get () when the memory is enough.
Soft references are often used to implement caching.

3. Weak references

Object obj = new Object();
WeakReference<Object> wf = new WeakReference<Object>(obj);
obj = null;
wf.get();//有时候会返回null
wf.isEnQueued();//返回是否被垃圾回收器标记为即将回收

A weak reference is in the second garbage recycling, even if memory is sufficient. By taking a short weak reference corresponding to the data, to be taken, when the second garbage collection performed, returns null

4. phantom reference

Object obj = new Object();
PhantomReference<Object> pf = new PhantomReference<Object>(obj);
obj=null;
pf.get();//永远返回null
pf.isEnQueued();//返回是否从内存中已经删除

When garbage collection, virtual reference will be recovered, and it does not refer to the same.


  • The method of garbage collection area of
    the main area of garbage collection heap, but garbage collection will happen the same way area. The recovery time for the young generation can recover 70% to 95% of the space, but the recovery efficiency of the permanent generation is much lower.
    Permanent generation garbage collection and disposal aimed at waste constants class.

Abandoned constant

Such as "abc" If you do not have any references, then recycled.

Class waste
recycling of the waste category needs to satisfy at three conditions:
all instances of the class have been recovered 1.
2. ClassLoader class has been recovered
3. java.lang.Class class corresponding to the object is referenced anywhere without

Note: You can set whether the class recovered by parameter -Xnoclassgc.

In the use of a large number of reflective, dynamic proxies, etc. CGLib ByteCode frame, and dynamically generated JSP OSGi Such frequent
custom ClassLoader scene class includes a virtual machine needs to unload function, in order to ensure permanent behalf does not overflow.


Guess you like

Origin www.cnblogs.com/guan-li/p/11505597.html