与软引用十分类似。
/** * 演示弱引用 * -Xmx20m -XX:+PrintGCDetails */ public class Demo2_5 { private static final int _4MB = 4 * 1024 * 1024; public static void main(String[] args) { // list --> WeakReference --> byte[] List<WeakReference<byte[]>> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { WeakReference<byte[]> ref = new WeakReference<>(new byte[_4MB]); list.add(ref); for (WeakReference<byte[]> w : list) { System.out.print(w.get()+" "); } System.out.println(); } System.out.println("循环结束:" + list.size()); } }
打印的结果如下。其中第10 次循环时,由于弱引用本身也占有一定的内存,触发Full GC。
[B@7f31245a [B@7f31245a [B@6d6f6e28 [B@7f31245a [B@6d6f6e28 [B@135fbaa4 [GC (Allocation Failure) [PSYoungGen: 2209K->504K(6144K)] 14497K->13139K(19968K), 0.0023913 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [B@7f31245a [B@6d6f6e28 [B@135fbaa4 [B@45ee12a7 [GC (Allocation Failure) [PSYoungGen: 4712K->496K(6144K)] 17347K->13326K(19968K), 0.0025155 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [B@7f31245a [B@6d6f6e28 [B@135fbaa4 null [B@330bedb4 [GC (Allocation Failure) [PSYoungGen: 4704K->504K(6144K)] 17534K->13350K(19968K), 0.0020861 secs] [Times: user=0.01 sys=0.00, real=0.00 secs] [B@7f31245a [B@6d6f6e28 [B@135fbaa4 null null [B@2503dbd3 [GC (Allocation Failure) [PSYoungGen: 4711K->504K(6144K)] 17557K->13382K(19968K), 0.0017767 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [B@7f31245a [B@6d6f6e28 [B@135fbaa4 null null null [B@4b67cf4d [GC (Allocation Failure) [PSYoungGen: 4710K->456K(6144K)] 17588K->13334K(19968K), 0.0017985 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [B@7f31245a [B@6d6f6e28 [B@135fbaa4 null null null null [B@7ea987ac [GC (Allocation Failure) [PSYoungGen: 4775K->504K(5120K)] 17653K->13398K(18944K), 0.0011480 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [B@7f31245a [B@6d6f6e28 [B@135fbaa4 null null null null null [B@12a3a380 [GC (Allocation Failure) [PSYoungGen: 4735K->256K(5632K)] 17629K->13531K(19456K), 0.0016537 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [Full GC (Ergonomics) [PSYoungGen: 256K->0K(5632K)] [ParOldGen: 13275K->782K(8192K)] 13531K->782K(13824K), [Metaspace: 3345K->3345K(1056768K)], 0.0108212 secs] [Times: user=0.17 sys=0.00, real=0.01 secs] null null null null null null null null null [B@29453f44 循环结束:10
当然,弱引用与软引用的区别是,只要触发垃圾回收,无论内存是否充足都会回收其引用对象。
public class WeakReferenceDemo { public static void main(String[] args) { WeakReference<String> sr = new WeakReference<String>( new String( "hello" )); System.out.println(sr.get()); System.gc(); //通知JVM的gc进行垃圾回收 System.out.println(sr.get()); } }
输出结果。
hello null