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 functionality. I can explain better with an example:
Say I'm making a game where money is involved. When a person picks up a Money object off the ground, I want to call that object's addTo method, which involves adding a value to that person's wallet.
public class Money {
/** The value of this object. */
private final int value;
// constructor
public Money(double x) {
this.value = x;
}
// Should be called when a Person picks up this object.
public void addTo(Person bob) {
bob.addToWallet(this.value);
}
// MAIN METHOD
public static void main(String[] args) {
Person bob = new Person();
Money dollar = new Money(1.00);
dollar.addTo(bob); // bob finds $1.00
}
}
After dollar is found, I don't want someone else to be able to pick it up. In other words, I don't want myself or any other program to be able to accidentally call the line:
dollar.addTo(alice);
So after Bob picks up the money, its value is added to his wallet and there's no need for an object representation of that value anymore. It's not that I care about the memory the object is using, but I don't want that object to be accidentally used somewhere else in the program. How do I destroy dollar besides setting dollar = null;?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With