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

来源:互联网 发布:xd mac 破解版 编辑:程序博客网 时间:2024/05/17 06:20

引用计数并清理对象

  类似于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);}}@Overridepublic 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();}@Overridepublic String toString() {return "Composing"+id;}}

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

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

0 0
原创粉丝点击