强弱引用

 

 

字符串常量是强引用, 对象是弱引用,使用弱引用管理对象,在内存不够下,通过手动调用GC实现节约开支目的

 

 

案例1:

 

/**
 * 引用分类:强、软、弱、虚
 * 强与弱引用
 * @author Administrator
 *
 */
public class RefDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		//testStrong();
		testWeak();
		
	}
	/**
	 * gc运行前:sina is very good
       gc运行后:null
	 */
	private static void testWeak() {
		
		//字符串对象
		String str =new String("sina is very good");
		//弱引用 管理 对象
		WeakReference<String> wr =new WeakReference<String>(str);
		System.out.println("gc运行前:"+wr.get());
		//断开引用
		str =null;
		//通知回收
		System.gc();
		System.runFinalization();
		//对象被回收
		System.out.println("gc运行后:"+wr.get());
	}
	/**
	 * 结果:
	 * gc运行前:sina is very good
       gc运行后:sina is very good

	 */
	public static void testStrong(){
		//字符串常量池  共享(不能回收)
		String str ="sina is very good";
		//弱引用 管理 对象
		WeakReference<String> wr =new WeakReference<String>(str);
		System.out.println("gc运行前:"+wr.get());
		//断开引用
		str =null;
		//通知回收
		System.gc();
		System.runFinalization();
		System.out.println("gc运行后:"+wr.get());
	}

}

 

 

案例2 WeakHashMap的使用:

 

	public static void main(String[] args) {
		WeakHashMap<String,String> map =new WeakHashMap<String,String>();
		//测试数据
		//常量池对象,不会回收  属于强引用
		map.put("abc", "a");
		map.put("d", "test");
		//gc运行 已被回收  
		map.put(new String("sina"), "c");
		map.put(new String("dsf"), "d");
		
		//通知回收
		System.gc();
		System.runFinalization();
		
		System.out.println(map.size()); // 结果是2   
	}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值