一、强引用 (存在该类型引用的对象时,不会回收对象,直到抛出 java.lang.OutOfMemoryError)
public static void strongReference() throws InterruptedException{ List list = new ArrayList(); while(true){ byte[] buf = new byte[10240000]; list.add(buf); for (Object object : list){ System.out.println(object); } System.out.println("******************"); Thread.sleep(100); } }
二、软引用 (当内存不足时,会对该类型的对象回收)
public static void softReference() throws InterruptedException{ List list = new ArrayList(); while(true){ byte[] buf = new byte[10240000]; list.add(new SoftReference(buf)); for (Object object : list){ SoftReference<Byte[]> ref = (SoftReference<Byte[]>) object; System.out.println(ref.get()); } System.out.println("******************"); Thread.sleep(100); } }
输出结果:开始内存充足时,list中的引用都指向可用内存,后来不足时,部分为null,说明被回收了
******************
[B@de6ced
[B@1fb8ee3
[B@14318bb
[B@10b30a7
[B@1b67f74
[B@69b332
[B@530daa
[B@a62fc3
[B@1270b73
[B@60aeb0
[B@16caf43
[B@66848c
[B@8813f2
[B@83cc67
[B@e09713
[B@de6f34
[B@156ee8e
[B@47b480
[B@10d448
[B@e0e1c6
[B@6ca1c
[B@1bf216a
[B@12ac982
******************
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
[B@c20e24
******************
三、弱引用 (只要gc执行,就回收对象,不论内存是否还够)
public static void weakReference() throws InterruptedException{ List list = new ArrayList(); while(true){ byte[] buf = new byte[10240000]; list.add(new WeakReference(buf)); for (Object object : list){ WeakReference<Byte[]> ref = (WeakReference<Byte[]>) object; System.out.println(ref.get()); } System.out.println("******************"); Thread.sleep(100); } }
结果:一开始执行时,内存充足时,就有null的情况,说明对象已被回收
[B@de6ced
******************
null
[B@1fb8ee3
******************
null
null
[B@14318bb
******************
null
null
null
[B@10b30a7
******************
null
null
null
null
[B@173a10f
******************
四、虚引用(相当于没用任何引用,对象可在任何时候被回收,虚引用需要和引用队列ReferenceQueue联合使用)
public static void phantomReference() throws InterruptedException{ List list = new ArrayList(); ReferenceQueue<byte[]> rq = new ReferenceQueue(); while(true){ byte[] buf = new byte[10240000]; PhantomReference<byte[]> ref = new PhantomReference(buf,rq); list.add(ref); System.out.println("ref = " + ref.get()); System.out.println("rq = " + rq.poll()); System.out.println("******************"); Thread.sleep(100); } }
结果:
ref = null
rq = null
******************
ref = null
rq = java.lang.ref.PhantomReference@c17164
******************