各种判断对像样否死亡的方法

各种判断对象是否死亡的方法
引用计数器
给对象中添加一个引用计数器,每当有一个地方引用它时,计数器值就加1;当引用失效时,计数器值就减1;任何时刻计数器都为0的对象就是不可能再被使用的

/** 
* testGC()方法执行后,objA和objB会不会被GC呢? 
* @author zzm 
*/ 
public class ReferenceCountingGC { 

	public Object instance = null; 

	private static final int _1MB = 1024 * 1024; 

	/** 
  * 这个成员属性的唯一意义就是占点内存,以便能在GC日志中看清楚是否被回收过 
  */ 
	private byte[] bigSize = new byte[2 * _1MB]; 

	public static void testGC() { 
		ReferenceCountingGC objA = new ReferenceCountingGC(); 
		ReferenceCountingGC objB = new ReferenceCountingGC(); 
		objA.instance = objB; 
		objB.instance = objA; 

		objA = null; 
		objB = null; 

		// 假设在这行发生GC,那么objA和objB是否能被回收? 
		System.gc();
	}
	public static void main(String[] args) {
		ReferenceCountingGC.testGC();
	}
}


[Full GC (System) [Tenured: 0K->150K(10944K), 0.0176003 secs] 4409K->150K(15872K), [Perm : 379K->379K(12288K)], 0.0177187 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
Heap
 def new generation   total 4992K, used 179K [0x229e0000, 0x22f40000, 0x27f30000)
  eden space 4480K,   4% used [0x229e0000, 0x22a0cda8, 0x22e40000)
  from space 512K,   0% used [0x22e40000, 0x22e40000, 0x22ec0000)
  to   space 512K,   0% used [0x22ec0000, 0x22ec0000, 0x22f40000)
 tenured generation   total 10944K, used 150K [0x27f30000, 0x289e0000, 0x329e0000)
   the space 10944K,   1% used [0x27f30000, 0x27f55a78, 0x27f55c00, 0x289e0000)
 compacting perm gen  total 12288K, used 379K [0x329e0000, 0x335e0000, 0x369e0000)
   the space 12288K,   3% used [0x329e0000, 0x32a3ef68, 0x32a3f000, 0x335e0000)
    ro space 10240K,  55% used [0x369e0000, 0x36f60f00, 0x36f61000, 0x373e0000)
    rw space 12288K,  55% used [0x373e0000, 0x37a842f0, 0x37a84400, 0x37fe0000)


4409K->150K(15872K)
说明GC内存回收了

根搜索算法

这个算法的基本思路就是通过一系列的名为“GC Roots”的对象作为起始点,从这些节点开始向下搜索,搜索所走过的路径称为引用链(Reference Chain),当一个对象到GC Roots没有任何引用链相连(用图论的话来说就是从GC Roots到这个对象不可达)时,则证明此对象是不可用的
在Java语言里,可作为GC Roots的对象包括下面几种:
  • 虚拟机栈(栈帧中的本地变量表)中的引用的对象。
  • 方法区中的类静态属性引用的对象。
  • 方法区中的常量引用的对象。
  • 本地方法栈中JNI(即一般说的Native方法)的引用的对象。


各种判断对像样否死亡的方法