Destroying objects in Java

后端 未结 8 750
走了就别回头了
走了就别回头了 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<Possession> {
      private final Map<Possession, Object> _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<Possession> 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);
      }
    }
    
    0 讨论(0)
  • 2021-01-22 00:29

    If you are really trying to model the real world as closely as possible, you could add a owner attribute to the dollar, so that when you call dollar.addTo(), you will have to change the owner, the dollar only belongs to one person at any given time.

    0 讨论(0)
  • 2021-01-22 00:37

    You have NO CONTROL over Java Garbage Collection -GC- and there is now way that you can force the Java Virtual Machine to destroy an object for you.

    You can call System.gc() [or Runtime.getRuntime().gc()] but that only suggests the JVM to run the Garbage Collection. The true is that the JVM is not supposed to listen to you for this and the GC execution is not guaranteed. Do not rely on that.

    Regarding your design need, put your money in a bank (or a street if you want people to find them) and ask the bank to give you one. Assuming that the bank has only 1, then subsequent calls will return null.

    EDIT AFTER DOWNVOTE

    I decided to remove some dust from my books and to quote a few lines from the Forcing Garbage Collection section of the 3rd chapter of the SCJP Study Guide. A book that I studied for pure masochism.

    The first thing that should be mentioned here is that, contrary to this section's title, garbage collection cannot be forced.

    ..it's recommended that you never invoke System.gc() in your code - leave it to the JVM.

    ..it is only possible to suggest to the JVM that it performs garbage collection. However, there are no guarantees the JVM will actually remove all of the unused objects from memory (even if garbage collection is run).

    Garbage Collection is a harder concept than it seems...

    0 讨论(0)
  • 2021-01-22 00:46

    You simply have to avoid making 'dollar' available to places you don't want it to go. Note that this isn't really a GC issue. For a non-GC environment (like C++) someone who somehow sees a pointer to an deleted object will crash and burn if they try accessing it.

    0 讨论(0)
  • 2021-01-22 00:47

    You shouldn't be thinking of garbage collection at all. It is up to the JVM to determine when things can be garbage collected and 99% of the time, you won't need to consider this at all if you program responsibly.

    Answer me this .. how would "the object be accidentally used somewhere else in the program"?

    The answer is, it couldn't. A local reference exists until the end of your main method and no longer. Unless you store a reference to it, it cannot be referenced.

    As your program grows, it might be a good idea to store a reference to it temporarily. You need to represent your concept of "the ground" with an object. Since the functionality you describe is basic, you can just use any of the built in implementations of Collection for example List.

    List<Money> floorMoney = new LinkedList<Money>();
    floorMoney.add(new Money(1.00));
    

    and when you associate money from the floor with a Person you would remove it from the floor.

    Money dollar = floorMoney.get(0); // how you access elements may vary
    floorMoney.remove(dollar);
    dollar.addTo(bob);
    

    Now, unless you store a reference to dollar somewhere in your addTo implementation, the Money object will be abandoned and later GC'd.

    0 讨论(0)
  • 2021-01-22 00:50

    why you cannot add a boolean "picked" default = false? or create a list and remove from it?

    0 讨论(0)
提交回复
热议问题