关于JAVA垃圾回收的一些小tips
public class AliveTest { public static AliveTest A = null; public static void alive(){ System.out.println("alive"); } protected void finalize() throws Throwable { super.finalize(); System.out.println("finalize"); AliveTest.A = this; //System.out.println(A); } public static void main(String[] args) throws InterruptedException { A = new AliveTest(); A=null; System.gc(); Thread.sleep(500); if(A!=null){ AliveTest.alive(); }else{ System.out.println("hehe"); } A=null; System.gc(); Thread.sleep(500); if(A!=null){ AliveTest.alive(); }else{ System.out.println("aa"); } } }
Java 虚拟机在垃圾回收的时候最多只调用一次 finalize 方法;
public class ReferenceTest { public static final Map<Integer, Reference> map = new HashMap<Integer, Reference>(); public static void main(String[] args) { for (int i = 0; i < 1000; i++) { map.put(i, new WeakReference(new ReferenceObject(i))); } int i = 0; for (Reference r : map.values()) { if (r.get() == null) { i++; } } System.out.println("被回收的对象数:" + i); } static class ReferenceObject { private int i; private byte[] b; public ReferenceObject(int i) { this.i = i; b = new byte[1024 *10000]; } } }
弱引用马上就会被回收掉。