Destroying objects in Java

后端 未结 8 754
走了就别回头了
走了就别回头了 2021-01-22 00:07

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

8条回答
  •  深忆病人
    2021-01-22 00:28

    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);
      }
    }
    

提交回复
热议问题