JVM garbage collection GC Roots Tracing

Original link: http://blog.csdn.net/u010744711/article/details/51371535

1. With search algorithm:

When the JVM memory recovery needs to judge whether the object is still in use, it can be discerned by GC Roots Tracing.

definition:

By a series of objects called "GCRoots" as a starting point, the search downwards from this node, the search path traversed referred ReferenceChain, when an object when not connected to any GCRoots ReferenceChain, (FIG theory: the unreachable objects) , then prove that this object is not available.

Here Insert Picture Description

GC Root can be used as a reference point is:

a. reference virtual machine stack (Local Variable Table stack frame in) objects
b. Method zone class static properties of object referenced
c. constant reference approach zone object
d. native method stack referenced the JNI Object

The main area of Java heap GC management is, in general, only for heap garbage collection. The method area, and a native method stack area is not managed by the GC, and thus select objects within those regions as GC roots, the referenced objects are not recovered GC roots GC.
A .GC how to determine an object as "rubbish"
java heap memory to store almost all the instances of objects, the garbage collector in front of the heap for recycling, the first thing is to determine which among these objects still "alive" with what had been "dead." So GC particular by what means to determine whether a target has been "dead" in?

1. The reference count algorithm (algorithm have been eliminated)
add a reference to the object counter in place whenever a reference to it, the counter value is incremented by 1; when referring to the failure, the counter value is decreased by 1; any time counter 0 objects is no longer being used.

Current mainstream java virtual machine are abandoned out of this algorithm, the main reason is that it is difficult to solve the problem of mutual circular references between objects. Despite the high efficiency of the algorithm.

For example: In testGC () method, the object fields are objA and objB instance, assignment and so objA.instance = objB objB.instance = objA, in addition to these two references to objects no longer have any, in fact, these two objects can no longer be accessed, since they refer to each other with the object side, their abnormal reference count is not 0, then the reference count algorithms can not notify them recovered GC collector.

2. reachability analysis algorithm
mainstream achieve mainstream programming languages (java, C #, etc.), a known whether all be determined by reachability analysis (Reachability Analysis) live objects. The basic idea of the algorithm is a series of objects referred to as "GC Roots" as a starting point, to start the search downward from these nodes, called search path traversed reference chain (Reference Chain), when an object to GC Roots without any reference chain connected (in the words of graph theory, it is from the GC Roots to this object is unreachable), then it proves that this object is not available. As shown below, target object 5, object 6, object 7 while associated with each other, but they are not up to the GC Roots, they would be determined to be recyclable objects.

Write pictures described here

II. GC is judged as "junk" objects will reclaim it
objects even in the reachability analysis algorithm unreachable, and it is not "Feisibuke", and this time they are temporarily in a "probation" stage, to really declared the death of an object, at least twice to go through the labeling process: If the object during reachability analysis found no references to the chain connected to the GC Roots, then it will be the first mark and conduct a screening, screening conditions this object is whether it is necessary to perform the finalize () method. When the object is not covered finalize () method, or a finalize () method has been invoked over the virtual machine, the virtual machine these two cases are considered "not necessary to perform." (Which means direct recycling)

If the object is determined to be necessary to perform a finalize () method, then the object will be placed in a queue called the F-Queue, and later by an automatic virtual machine created by the low-priority thread Finalizer to execute it. Here, the term "execution" refers to the virtual machine to trigger this method, but it does not promise it will wait for the end of the run, the reason for this is that, if an object is performed finalize () method is slow, or the occurrence of an infinite loop (more extreme case), will likely lead to F-queue queue other objects permanently in wait, and even cause the entire memory recovery system crash.

finalize () method is the last chance to escape death fate of the object, later GC will be F-Queue object in a second small mark, if the object to be successful in their own rescue finalize () in - just to reconnect with any reference to an object on the chain can be associated, such as his own (this keyword) assigned to the member variables of a class variable or an object, then it will be removed out "will be recovered" at the second mark collection; if the object has not escaped this time, it really is that essentially recovered.

Code Example:

public class FinalizeEscapeGC {
public static FinalizeEscapeGC SAVE_HOOK = null;

public void isAlive() {
    System.out.println("yes,i am still alive:)");
}

@Override
protected void finalize() throws Throwable {
    super.finalize();
    System.out.println("finalize mehtod executed!");
    FinalizeEscapeGC.SAVE_HOOK = this;
}

public static void main(String[] args) throws Throwable {
    SAVE_HOOK = new FinalizeEscapeGC();
    // 对象第一次成功拯救自己
    SAVE_HOOK = null;
    System.gc();
    // 因为finalize方法优先级很低,所以暂停0.5秒以等待它
    Thread.sleep(500);
    if (SAVE_HOOK != null) {
        SAVE_HOOK.isAlive();
    } else {
        System.out.println("no,i am dead:(");
    }
    // 下面这段代码与上面的完全相同,但是这次自救却失败了
    SAVE_HOOK = null;
    System.gc();
    // 因为finalize方法优先级很低,所以暂停0.5秒以等待它
    Thread.sleep(500);
    if (SAVE_HOOK != null) {
        SAVE_HOOK.isAlive();
    } else {
        System.out.println("no,i am dead:(");
    }
}

}

operation result:

mehtod the Executed the Finalize!
yes, i AM Still Alive :)
NO, i AM Dead :(
the Finalize SAVE_HOOK object () method does is triggered GC collector, and managed to escape before being collected. Also worth noting is , exactly the same code has two code snippets, escaped execution result is a success, a failure, because finalize any object () method will only call the system automatically, once a recovery next if the object is facing, it's finalize () method will not be executed again, and therefore the second paragraph of the code of self-help action failed because the finalize () method has been invoked over the virtual machine, the virtual machine is treated as "there is no need to perform." (which means direct recycling)

finalize () method

Generally describe the finalize process: when an object becomes (GC Roots) is not reachable, the GC will determine whether the object covered finalize method, if not covered, will be directly recovered. Otherwise, if the object has not been performed finalize method, put it into F-Queue queue, the queue objects finalize method is performed by a low-priority thread. After the completion of execution finalize method, GC will determine whether the object can reach, if not reach, then recovered again. Otherwise, the object "resurrection."

Garbage collector ready to release memory when will first call finalize ().

(1) The object will not necessarily be recycled.

   (2).垃圾回收不是析构函数。

   (3).垃圾回收只与内存有关。

   (4).垃圾回收和finalize()都是靠不住的,只要JVM还没有快到耗尽内存的地步,它是不会浪费时间进行垃圾回收

      之所以要使用finalize(),是存在着垃圾回收器不能处理的特殊情况。假定你的对象(并非使用new方法)获得了一块“特殊”的内存区域,由于垃圾回收器只知道那些显示地经由new分配的内存空间,所以它不知道该如何释放这块“特殊”的内存区域,那么这个时候Java允许在类中定义一个由finalize()方法。
  特殊的区域例如:1)由于在分配内存的时候可能采用了类似C语言的做法,而非JAVA的通常new做法。这种情况主要发生在native method中,比如native method调用了C/C++方法malloc()函数系列来分配存储空间,但是除非调用free()函数,否则这些内存空间将不会得到释放,那么这个时候就可能造成内存泄漏。但是由于free()方法是在C/C++中的函数,所以finalize()中可以用本地方法来调用它。以释放这些“特殊”的内存空间。2)又或者打开的文件资源,这些资源不属于垃圾回收器的回收范围。



  换言之,finalize()的主要用途是释放一些其他做法开辟的内存空间,以及做一些清理工作。因为在JAVA中并没有提够像“析构”函数或者类似概念的函数,要做一些类似清理工作的时候,必须自己动手创建一个执行清理工作的普通方法,也就是override Object这个类中的finalize()方法。例如,假设某一个对象在创建过程中会将自己绘制到屏幕上,如果不是明确地从屏幕上将其擦出,它可能永远都不会被清理。如果在finalize()加入某一种擦除功能,当GC工作时,finalize()得到了调用,图像就会被擦除。要是GC没有发生,那么这个图像就会被一直保存下来。

    一旦垃圾回收器准备好释放对象占用的存储空间,首先会去调用finalize()方法进行一些必要的清理工作。只有到下一次再进行垃圾回收动作的时候,才会真正释放这个对象所占用的内存空间。



   在普通的清除工作中,为清除一个对象,那个对象的用户必须在希望进行清除的地点调用一个清除方法。这与C++"析构函数"的概念稍有抵触。在C++中,所有对象都会破坏(清除)。或者换句话说,所有对象都"应该"破坏。若将C++对象创建成一个本地对象,比如在堆栈中创建(在Java中是不可能的,Java都在堆中),那么清除或破坏工作就会在"结束花括号"所代表的、创建这个对象的作用域的末尾进行。若对象是用new创建的(类似于Java),那么当程序员调用C++的 delete命令时(Java没有这个命令),就会调用相应的析构函数。若程序员忘记了,那么永远不会调用析构函数,我们最终得到的将是一个内存"漏洞",另外还包括对象的其他部分永远不会得到清除。

In contrast, Java does not allow us to create a local (local) objects - in any case to use new. But in Java, there is no "delete" command to release the object, because the garbage collector will automatically help us free up storage space. So if standing position to simplify the comparison, we can say that it is precisely because there is garbage collection mechanism, so Java does not have destructors. However, with the in-depth study of the future, will be aware of the existence of the garbage collector can not completely eliminate the need for a destructor, or that does not eliminate the need for (see next paragraph reason that the mechanism of the destructor representatives. In addition finalize () function in the garbage collector is ready to release the memory occupied by objects when they were called, must not directly call finalize (), you should try to avoid using it). If you want to perform some other form of free storage space in addition to work outside of the clear, still you must call a method in Java. It is equivalent to the C ++ destructor, but the latter is not convenient.

  在C++中所有的对象运用delete()一定会被销毁,而JAVA里的对象并非总会被垃圾回收器回收。In another word, 1 对象可能不被垃圾回收,2 垃圾回收并不等于“析构”,3 垃圾回收只与内存有关。也就是说,并不是如果一个对象不再被使用,是不是要在finalize()中释放这个对象中含有的其它对象呢?不是的。因为无论对象是如何创建的,垃圾回收器都会负责释放那些对象占有的内存。

reference:

http://blog.csdn.net/u010744711/article/details/51371535

http://blog.csdn.net/time_hunter/article/details/12405127

Guess you like

Origin blog.csdn.net/shiningdreamercaihua/article/details/102753912