要應用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:
