Skip to content

Instantly share code, notes, and snippets.

@sanpingz
Created May 25, 2012 04:02
Show Gist options
  • Save sanpingz/2785678 to your computer and use it in GitHub Desktop.
Save sanpingz/2785678 to your computer and use it in GitHub Desktop.
引用计数器
import static com.mceiba.util.Print.*;
class Shared{
private int refcount = 0;
private static long counter = 0;
private final long id = counter++;
public void shared(){
println("Creating "+this);
}
public void addRef() { refcount++; }
protected void dispose(){
if(--refcount == 0){
println("Disposing "+this);
}
}
public String toString() { return "Shared "+id;}
}
class Composing{
private Shared shared;
private static long counter = 0;
private final long id = counter++;
public Composing(Shared shared){
println("Creating "+this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose(){
println("disposing "+this);
shared.dispose();
}
public String toString() { return "Composing "+id; }
}
public class RefCounting{
public static void main(String[] args){
Shared shared = new Shared();
Composing[] composing = {
new Composing(shared),
new Composing(shared),
new Composing(shared),
new Composing(shared),
new Composing(shared),
new Composing(shared),
new Composing(shared)
};
for(Composing c: composing) c.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment