Java 父类和子类对象销毁实例

1)定义一个共享类Shared

使用long而不使用int,是为了防止溢出,refcount是共享类被其他类引用的次数,只要还有其他的类引用这个类,共享类就不会被GC回收。

package cn.javass.user;

public class Shared {
 private int refcount=0;
 private static long counter=0;
 private final long id=counter++;
 
 public Shared(){
  System.out.println("Creating "+this);
 }
 
 public void addRef(){refcount++;};
 
 protected void dispose(){
  if(--refcount==0){
   System.out.println("Disposing "+this);
  }
 }
 
 //重写toString方法
 public String toString(){return "Shared"+id;};
}

2)定义一个组合类

package cn.javass.user;

public class Composing {

 private Shared shared;
 private static long counter=0;
 private final long id=counter++;
 
 public Composing(Shared shared) {
  // TODO Auto-generated constructor stub
  System.out.println("Creating "+this);
  this.shared=shared;
  this.shared.addRef();
 }
 
 protected void dispose(){
  System.out.println("disposing "+this);
  shared.dispose();
 }
 
 public String toString(){return "Composing" +id; };
}

3)定义引用计数类

package cn.javass.user;

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(Composing c:composings)
   c.dispose();
 }
}

 

阅读更多
个人分类: java开发
上一篇Struts Action实例化
下一篇java,构造函数内部的多态行为
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭