示例代碼
import java.util.ArrayList;
import java.util.List;
public class StaticFieldClass {
public static List<Team> staticField1 = new ArrayList<Team>();
static {
staticField1.add(new Team());
staticField1.add(new Team());
}
}
staticField1 字段引用Team的對象,Team對象肯定不會被GC回收,但是這是為什么?
靜態字段是不是GC ROOT,如果不是那是誰
將代碼跑起來,並將堆dump下來,借助MAT分析。
在Histogram視圖找到Team實例:
然后 右鍵找到的Team對象-> List Objects -> With incoming references
然后 右鍵找到的Team對象-> Path TO GC Roots -> exclude All Phantom...
不難看出,靜態字段不是GC ROOT,GC ROOT是Thread...
Thread持有contextClassLoader,Classloader再持有靜態字段...
同時MAT還提供了直接查看GC ROOT的功能,我們也可以順着GC ROOT往下找到我們的對象。