各种判断对象是否死亡的方法
引用计数器
给对象中添加一个引用计数器,每当有一个地方引用它时,计数器值就加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)
