I have a general idea of how the Garbage Collector works in Java, but my reasoning for destroying an object is not because I care about freeing up memory, but because of functio
As an extension to what @pstanton said, keep collections of owned objects. Here's an elaborate way, which is useful for preventing mistaken code from corrupting your state.
public abstract class Possession {
private Object _key = null;
public synchronized Object acquire() {
if (_key != null) { throw new IllegalStateException(); }
_key = new Object();
}
public synchronized void release(Object key) {
if (_key != key) { throw new IllegalStateException(); }
_key = null;
}
}
public class Possessions implements Iterable {
private final Map _possessions = new IdentityHashMap<...>();
public synchronized void add(Possession p) {
if (!_possessions.containsKey(p)) {
_possessions.put(p, p.acquire());
}
}
public synchronized void remove(Possession p) {
Object key = _possessions.remove(p);
if (key != null) {
p.release(key);
}
}
public Iterator iterator() {
return Collections.unmodifiableSet(_possessions.keySet()).iterator();
}
}
public class Money extends Possession { ... }
public class Person {
private final Possessions _possessions = new Possessions();
public void add(Money money) {
_possessions.add(money);
}
}