判定对象是否存活的算法----GC_ROOT算法
阅读原文时间:2023年09月28日阅读:3

要应用GC_ROOT算法,判定某个对象是否会被回收,关键是要确定root。确定root之后,你就可以根据代码绘制可达链,从而就可以进行分析了,分析哪些对象会被泄漏,哪些对象会被回收,如果GC执行的时候。

可以作为root的对象:

1.类中的静态变量,当它持有一个指向一个对象的引用时,它就作为root

2.活动着的线程,可以作为root

3.一个Java方法的参数或者该方法中的局部变量,这两种对象可以作为root

4.JNI方法中的局部变量或者参数,这两种对象可以作为root

其它。

其中:第1种是类的类型信息,加载在方法区中;第3种,是存放在虚拟机栈的栈帧中,一个线程调用一个java方法,java虚拟机就会使用一个栈帧保存该方法的调用状态,该栈帧入栈到该线程所对应的虚拟机栈中;第4种,是存放在一个线程的本地栈中。

例子:下述的Something和Apple都可以作为root对象。

public AClass{

public static Something;
public static final Apple;

''''''

}

Java方法的参数和方法中的局部变量,可以作为root.

public Aclass{

public void doSomething(Object A)
{
ObjectB b = new ObjectB;

}
}

//某个线程执行该方法时,参数A可以作为root;
// 局部变量b,也可以作为参数。

-------------------------------------------------我是分割线--------------------------------------------------------------------------------------------

//参考资料:

http://www.yourkit.com/docs/80/help/gc_roots.jsp

http://www.cnblogs.com/zuoxiaolong/p/jvm3.html

GC roots

The so-called GC (Garbage Collector) roots are objects special for garbage collector. Garbage collector collects those objects that are not GC roots and are not accessible by references from GC roots.

There are several kinds of GC roots. One object can belong to more than one kind of root. The root kinds are:

  • Class - class loaded by system class loader. Such classes can never be unloaded. They can hold objects via static fields. Please note that classes loaded by custom class loaders are not roots, unless corresponding instances of java.lang.Class happen to be roots of other kind(s).
  • Thread - live thread
  • Stack Local - local variable or parameter of Java method
  • JNI Local - local variable or parameter of JNI method
  • JNI Global - global JNI reference
  • Monitor Used - objects used as a monitor for synchronization
  • Held by JVM - objects held from garbage collection by JVM for its purposes. Actually the list of such objects depends on JVM implementation. Possible known cases are: the system class loader, a few important exception classes which the JVM knows about, a few pre-allocated objects for exception handling, and custom class loaders when they are in the process of loading classes. Unfortunately, JVM provides absolutely no additional detail for such objects. Thus it is up to the analyst to decide to which case a certain "Held by JVM" belongs.

If an object is a root, it is specially marked in all views showing individual objects. For example, the following picture shows a fragment of paths view: