标签:unlock nsa 16px sys dex protected zhang omr 24*
一个变量指向new对象,就是引用,在java中有四种引用,分别是强软弱虚,常见的Object o = new Object(),就是强引用,垃圾回收的时候,强引用不会被回收。
public class M { @Override protected void finalize() throws Throwable { System.out.println("finalize"); } }
public class T01_NormalReference { public static void main(String[] args) throws IOException { M m = new M(); m = null;//只有没有引用时,M的对象m才会被回收 System.gc(); //DisableExplicitGC System.in.read();//阻塞线程的目的是:因为GC是运行在其他线程中的,不阻塞很可能还没开始回收,线程就已经结束了。 } }
public class T02_SoftReference { public static void main(String[] args) { SoftReference<byte[]> m = new SoftReference<>(new byte[1024*1024*10]); //m = null; System.out.println(m.get()); System.gc(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(m.get()); //再分配一个数组,heap将装不下,这时候系统会垃圾回收,先回收一次,如果不够,会把软引用干掉,此时打印的结果应该是空置 byte[] b = new byte[1024*1024*15]; System.out.println(m.get()); } }
public class T03_WeakReference { public static void main(String[] args) { WeakReference<M> m = new WeakReference<>(new M()); System.out.println(m.get()); System.gc(); System.out.println(m.get()); ThreadLocal<M> tl = new ThreadLocal<>(); tl.set(new M()); tl.remove();//必须ThreadLocal用完必须remove,否则还是有内存泄漏 } }
public class ThreadLocal2 { static ThreadLocal<Person> tl = new ThreadLocal<>(); public static void main(String[] args) { new Thread(()->{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } tl.set(new Person()); }).start(); } static class Person { String name = "zhangsan"; } }
例子图示:
public class T04_PhantomReference { private static final List<Object> LIST = new LinkedList<>(); private static final ReferenceQueue<M> QUEUE = new ReferenceQueue<>(); public static void main(String[] args) { PhantomReference<M> phantomReference = new PhantomReference<>(new M(), QUEUE); new Thread(() -> { while (true) { LIST.add(new byte[1024 * 1024]); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } System.out.println(phantomReference.get()); } }).start(); new Thread(() -> { while (true) { Reference<? extends M> poll = QUEUE.poll(); if (poll != null) { System.out.println("--- 虚引用对象被jvm回收了 ---- " + poll); } } }).start(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }
标签:unlock nsa 16px sys dex protected zhang omr 24*
原文地址:https://www.cnblogs.com/Courage129/p/12734506.html