测试WeakReference和PhantomReference

介绍强引用(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();  
		} 
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值