正文
public
ReferenceCountingGC
(
String name
)
{
}
}
public
static
void
testGC
(
)
{
ReferenceCountingGC a
=
new
ReferenceCountingGC
(
"objA"
)
;
ReferenceCountingGC b
=
new
ReferenceCountingGC
(
"objB"
)
;
a
.
instance
=
b
;
b
.
instance
=
a
;
a
=
null
;
b
=
null
;
}
1. 定义2个对象
2. 相互引用
3. 置空各自的声明引用
我们可以看到,最后这2个对象已经不可能再被访问了,但由于他们相互引用着对方,导致它们的引用计数永远都不会为0,通过引用计数算法,也就永远无法通知GC收集器回收它们。
可达性分析算法
可达性分析算法(Reachability Analysis)的基本思路是,通过一些被称为引用链(GC Roots)的对象作为起点,从这些节点开始向下搜索,搜索走过的路径被称为(Reference Chain),当一个对象到 GC Roots 没有任何引用链相连时(即从 GC Roots 节点到该节点不可达),则证明该对象是不可用的。
通过可达性算法,成功解决了引用计数所无法解决的问题-“循环依赖”,只要你无法与 GC Root 建立直接或间接的连接,系统就会判定你为可回收对象。
那这样就引申出了另一个问题,哪些属于 GC Root。
Java 内存区域
在 Java 语言中,可作为 GC Root 的对象包括以下4种:
虚拟机栈(栈帧中的本地变量表)中引用的对象
此时的 s,即为 GC Root,当s置空时,localParameter 对象也断掉了与 GC Root 的引用链,将被回收。
public class StackLocalParameter {
public StackLocalParameter(String name){}
}
public static void testGC(){
StackLocalParameter s = new StackLocalParameter("localParameter");
s = null;
}
方法区中类静态属性引用的对象