Created
May 25, 2012 04:02
-
-
Save sanpingz/2785678 to your computer and use it in GitHub Desktop.
引用计数器
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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