2015-09-07 11:44:36 -06:00
|
|
|
|
// polymorphism/ReferenceCounting.java
|
2015-11-14 16:18:05 -08:00
|
|
|
|
// <20>2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
|
// Cleaning up shared member objects.
|
|
|
|
|
|
|
|
|
|
class Shared {
|
|
|
|
|
private int refcount = 0;
|
|
|
|
|
private static long counter = 0;
|
|
|
|
|
private final long id = counter++;
|
|
|
|
|
public Shared() {
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("Creating " + this);
|
2015-06-15 17:47:35 -07:00
|
|
|
|
}
|
|
|
|
|
public void addRef() { refcount++; }
|
|
|
|
|
protected void dispose() {
|
|
|
|
|
if(--refcount == 0)
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("Disposing " + this);
|
2015-06-15 17:47:35 -07:00
|
|
|
|
}
|
|
|
|
|
@Override
|
|
|
|
|
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) {
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("Creating " + this);
|
2015-06-15 17:47:35 -07:00
|
|
|
|
this.shared = shared;
|
|
|
|
|
this.shared.addRef();
|
|
|
|
|
}
|
|
|
|
|
protected void dispose() {
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("disposing " + this);
|
2015-06-15 17:47:35 -07:00
|
|
|
|
shared.dispose();
|
|
|
|
|
}
|
|
|
|
|
@Override
|
|
|
|
|
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) };
|
|
|
|
|
for(Composing c : composing)
|
|
|
|
|
c.dispose();
|
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
|
}
|
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
|
Creating Shared 0
|
|
|
|
|
Creating Composing 0
|
|
|
|
|
Creating Composing 1
|
|
|
|
|
Creating Composing 2
|
|
|
|
|
Creating Composing 3
|
|
|
|
|
Creating Composing 4
|
|
|
|
|
disposing Composing 0
|
|
|
|
|
disposing Composing 1
|
|
|
|
|
disposing Composing 2
|
|
|
|
|
disposing Composing 3
|
|
|
|
|
disposing Composing 4
|
|
|
|
|
Disposing Shared 0
|
2015-09-07 11:44:36 -06:00
|
|
|
|
*/
|