记录一次TIJ中提出的对象引用计数法

引用计数并清理对象

  类似于C++中的析构函数,Java中自定义对象的销毁应遵循与初始化相反的顺序清理对象
  然而如果这些成员对象中存在与其他一个或多个对象共享的情况,也许就必须使用引用计数来跟踪共享对象的数量了。
package z8;

/**
 * 引用计数器
 * @author 涛
 *
 */
public class ReferenceCounting {
	public static void main(String[] args) {
		Shared shared = new Shared();
		Composing [ ]  composings= {
				new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared)
		};
		for (int i = 0; i < composings.length; i++) {
			composings[i].dispose();
		}
	}
}

class Shared {
	private int refcount  = 0;
	private static long counter= 0;  //counter 使用long 而不是int 是为了防止溢出,这是一个良好的实践
	private final long id = counter ++;  //id 是final的,是为了在生命周期内不会改变
	public Shared() {
		System.out.println("Creating "+this);
	}
	public void addRef(){
		refcount++;
	}
	
	public void dispose(){
		if( --refcount == 0){
			System.out.println("Disposing"+this);
		}
	}
	
	@Override
	public String toString() {
		return "Shared"+id;
	}
	
}//Shared 结束

class Composing{
	private Shared shared;
	private static long counter = 0;
	private final long id = counter++;
	
	public Composing(Shared shared){
		System.out.println("Creating"+this);
		this.shared = shared;
		this.shared.addRef();
	}
	protected void dispose(){
		System.out.println("dispose "+this);
		shared.dispose();
	}
	
	@Override
	public String toString() {
		return "Composing"+id;
	}
}

 
 

在一个共享对象附着到类上时,必须记得调用addRef(),但是dispose()方法将跟踪引用数,并决定何时执行清理。

使用这种技巧必须倍加小心,但是如果你正在共享需要清理的对象,就没有太大的选择余地了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值