示例代码

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实例:
静态字段引用的对象为什么不会被GC回收

然后 右键找到的Team对象-> List Objects -> With incoming references
静态字段引用的对象为什么不会被GC回收

然后 右键找到的Team对象-> Path TO GC Roots -> exclude All Phantom...
静态字段引用的对象为什么不会被GC回收

静态字段引用的对象为什么不会被GC回收

不难看出,静态字段不是GC ROOT,GC ROOT是Thread...
Thread持有contextClassLoader,Classloader再持有静态字段...

同时MAT还提供了直接查看GC ROOT的功能,我们也可以顺着GC ROOT往下找到我们的对象。
静态字段引用的对象为什么不会被GC回收
静态字段引用的对象为什么不会被GC回收

相关文章:

  • 2021-06-12
  • 2021-04-16
  • 2022-12-23
  • 2021-07-16
  • 2022-12-23
  • 2022-12-23
  • 2021-09-03
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2021-07-15
  • 2021-10-25
  • 2021-11-03
  • 2022-12-23
相关资源
相似解决方案