OnJava8-Examples/polymorphism/ReferenceCounting.java

72 lines
1.6 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// polymorphism/ReferenceCounting.java
2016-12-30 17:23:13 -08:00
// (c)2017 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.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Cleaning up shared member objects
2015-06-15 17:47:35 -07:00
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
2016-01-25 18:05:55 -08:00
public String toString() {
return "Shared " + id;
}
2015-06-15 17:47:35 -07:00
}
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
2016-01-25 18:05:55 -08:00
public String toString() {
return "Composing " + id;
}
2015-06-15 17:47:35 -07:00
}
public class ReferenceCounting {
public static void main(String[] args) {
Shared shared = new Shared();
2016-01-25 18:05:55 -08:00
Composing[] composing = {
new Composing(shared),
new Composing(shared),
new Composing(shared),
new Composing(shared),
new Composing(shared)
};
2015-06-15 17:47:35 -07:00
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
*/