赞
踩
//Java不是使用引用计数算法 public class ReferenceCountGC { private byte[] bigSize = new byte[5 * 1024 * 1024]; Object reference = null; public static void main(String[] args) { ReferenceCountGC obj1 = new ReferenceCountGC(); ReferenceCountGC obj2 = new ReferenceCountGC(); obj1.reference = obj2; obj2.reference = obj1; obj1 = null; obj2 = null; //显示执行垃圾回收 System.gc(); } } //执行时添加参数-XX:+PrintGCDetails,不显示执行System.gc(),结果如下 Heap PSYoungGen total 152576K, used 20726K [0x0000000716300000, 0x0000000720d00000, 0x00000007c0000000) eden space 131072K, 15% used [0x0000000716300000,0x000000071773d8d8,0x000000071e300000) from space 21504K, 0% used [0x000000071f800000,0x000000071f800000,0x0000000720d00000) to space 21504K, 0% used [0x000000071e300000,0x000000071e300000,0x000000071f800000) ParOldGen total 348160K, used 0K [0x00000005c2800000, 0x00000005d7c00000, 0x0000000716300000) object space 348160K, 0% used [0x00000005c2800000,0x00000005c2800000,0x00000005d7c00000) Metaspace used 3425K, capacity 4496K, committed 4864K, reserved 1056768K class space used 380K, capacity 388K, committed 512K, reserved 1048576K //执行时添加参数-XX:+PrintGCDetails,显示执行System.gc(),结果如下, [GC (System.gc()) [PSYoungGen: 18104K->808K(152576K)] 18104K->816K(500736K), 0.0021479 secs] [Times: user=0.00 sys=0.00, real=0.02 secs] [Full GC (System.gc()) [PSYoungGen: 808K->0K(152576K)] [ParOldGen: 8K->645K(348160K)] 816K->645K(500736K), [Metaspace: 3476K->3476K(1056768K)], 0.0034007 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] Heap PSYoungGen total 152576K, used 3932K [0x0000000716300000, 0x0000000720d00000, 0x00000007c0000000) eden space 131072K, 3% used [0x0000000716300000,0x00000007166d7230,0x000000071e300000) from space 21504K, 0% used [0x000000071e300000,0x000000071e300000,0x000000071f800000) to space 21504K, 0% used [0x000000071f800000,0x000000071f800000,0x0000000720d00000) ParOldGen total 348160K, used 645K [0x00000005c2800000, 0x00000005d7c00000, 0x0000000716300000) object space 348160K, 0% used [0x00000005c2800000,0x00000005c28a1460,0x00000005d7c00000) Metaspace used 3491K, capacity 4498K, committed 4864K, reserved 1056768K class space used 387K, capacity 390K, committed 512K, reserved 1048576K
/** * 测试object中finalize()方法,即对象finalization */ public class CanReliveObj { public static CanReliveObj obj; //此方法只调用1次 @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("调用当前类重写finalize方法"); obj = this; //当前对象在finalize()方法中与引用链上的一个对象建立联系 } public static void main(String[] args) throws InterruptedException { obj = new CanReliveObj(); //对象第一次成功拯救自己 obj = null; System.out.println("第1次gc"); System.gc(); Thread.sleep(2000); if (obj == null) { System.out.println("obj is dead"); } else { System.out.println("obj is still alive"); } System.out.println("第2次gc"); obj = null; System.gc(); } } //执行结果 第1次gc 调用当前类重写finalize方法 obj is still alive 第2次gc
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。