-
java中的四种引用:强软弱虚
-
强引用:M m =new M(); 只有当没有任何引用指向M对象时,才会被回收
public class T01_NormalReference { public static void main(String[] args) { M m = new M(); m = null; System.gc(); } }
-
软引用:SoftReference<byte[]> m = new SoftReference<>(new byte[1024 * 1024 * 10]);系统会垃圾回收,先回收一次,如果不够,会把软引用干掉,适合用作缓存
public class T02_SoftReference { //-Xmx20M 堆内存最大20m public static void main(String[] args) { SoftReference<byte[]> m = new SoftReference<>(new byte[1024 * 1024 * 10]);//10m 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];//15m System.out.println(m.get()); } }
-
弱引用:WeakReference m = new WeakReference<>(new M());一次性,碰到gc就会被回收
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(); } }
-
虚引用:PhantomReference phantomReference = new PhantomReference<>(new M(), QUEUE);管理堆外内存DirectByteBuffer
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(); } } }
-
java中的四种引用:强软弱虚
最新推荐文章于 2022-07-15 15:13:10 发布
本文详细介绍了Java中的四种引用类型:强引用、软引用、弱引用和虚引用。强引用是最常见的引用类型,只有当没有其他引用指向对象时才会被垃圾回收。软引用常用于缓存,系统会在内存不足时回收。弱引用一旦遇到垃圾回收就会被清除。虚引用则用于管理堆外内存,与引用队列配合使用,在对象被回收后通知。通过示例代码展示了四种引用类型的使用和效果。
摘要由CSDN通过智能技术生成