package reference;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
public class ReferenceTest {
public static void main(String[] args) {
System.out.println("弱引用==============");
testWeakReference();
System.out.println("软引用==============");
testSoftReference();
System.out.println("虚引用==============");
testPhantomReference();
}
/**
* 测试弱引用
*/
private static void testWeakReference() {
Object obj = new Object();
// 构建弱引用
ReferenceQueue refQueue = new ReferenceQueue();
WeakReference weakRef = new WeakReference(obj, refQueue);
// 关联对象
System.out.println(weakRef.get());
// 检查入队情况
System.out.println(refQueue.poll());
obj = null;
System.gc();
// 延迟,等待入队操作执行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 关联对象是否回收
System.out.println(weakRef.get());
// 是否入队
System.out.println(refQueue.poll());
}
/**
* 测试软引用
*/
private static void testSoftReference() {
Object obj = new Object();
ReferenceQueue refQueue = new ReferenceQueue();
SoftReference weakRef = new SoftReference(obj, refQueue);
// 关联对象
System.out.println(weakRef.get());
// 检查入队情况
System.out.println(refQueue.poll());
obj = null;
System.gc();
// 延迟,等待入队操作执行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 关联对象是否回收
System.out.println(weakRef.get());
// 是否入队
System.out.println(refQueue.poll());
}
/**
* 测试虚引用
*/
private static void testPhantomReference() {
Object obj = new Object();
ReferenceQueue refQueue = new ReferenceQueue();
PhantomReference weakRef = new PhantomReference(obj, refQueue);
// 关联对象
System.out.println(weakRef.get());
// 检查入队情况
System.out.println(refQueue.poll());
obj = null;
System.gc();
// 延迟,等待入队操作执行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 关联对象是否回收
System.out.println(weakRef.get());
// 是否入队
System.out.println(refQueue.poll());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Phantom Reference's referent recycled.");
}
}