介绍强引用(strong reference)、软引用(soft reference)、弱引用(weak reference)和虚引用(phantom reference)
下面测试WeakReference和PhantomReference
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
public class ReferenceTest {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Reference<Object> ref;
Object weakObj = new String("weak reference");
Object phantomObj = new String("phantom reference");
ReferenceQueue<Object> weakQueue = new ReferenceQueue<Object>();
ReferenceQueue<Object> phantomQueue = new ReferenceQueue<Object>();
WeakReference<Object> weakReference = new WeakReference<Object>(weakObj, weakQueue);
PhantomReference<Object> phantomReference = new PhantomReference<Object>(phantomObj, phantomQueue);
weakObj = null;
phantomObj = null;
System.out.println("Weak Reference: "+weakReference.get());
System.out.println("Phantom Reference: "+phantomReference.get());//null
System.gc();//弱引用、虚引用被回收,同时加入到相关ReferenceQueue
System.out.println("Weak Reference: "+weakReference.get());//null
System.out.println("Phantom Reference: "+phantomReference.get());//null
if(!phantomReference.isEnqueued()) {
System.out.println("Request finalization.");
System.runFinalization();
}
System.out.println("weak is queued: "+weakReference.isEnqueued());//true
System.out.println("Phantom Queued: " + phantomReference.isEnqueued());//true
try {
ref = (Reference<Object>) weakQueue.remove();
System.out.println("Weak Reference: " + ref.get());//null
ref = (Reference<Object>) phantomQueue.remove();
System.out.println("Phantom Reference: " + ref.get());//null
ref.clear();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}