-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReferenceCounting.java
More file actions
55 lines (53 loc) · 1.38 KB
/
Copy pathReferenceCounting.java
File metadata and controls
55 lines (53 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Shared{
private int refcount = 0;
private static long counter = 0;
private final long id = counter++;
public Shared(){
System.out.println("Creating " + this);
}
public int addRef(){
return refcount++;
}
protected void dispose(){
if(--refcount==0){
System.out.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){
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;
}
}
public class ReferenceCounting{
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),
new Composing(shared),
};
for(Composing c: composing)
c.dispose();
}
}