Kenneth Wang
Kenneth Wang

Reputation: 191

Java Garbage Collection regarding class instances

I am a bit confused on how to utilize Java's Garbage Collection to dispose of instances of objects that aren't in use anymore. I have a few questions:

In my game, I generate Cannons without storing them in a variable like so:

        new Cannon("down", tileX, tileY, 65);

Will this object always be eligible for garbage collection? If yes, then when will it actually be disposed of?

==

For my Cannon class, I add all instances to a static array list upon creation. This was my first attempt at using the garbage collection:

    ArrayList<Cannon> cannonList = Cannon.getCannons();
    for (int i = 0; i < cannonList.size(); i++) {
        Cannon c = (Cannon) cannonList.get(i);
        c = null;
    }
    for (int i = 0; i < cannonList.size(); i++) {
        cannonList.remove(i);
    }
   System.gc();

When I set "c = null;", does it make the original Cannon to "null", thus making it eligible for garbage collection, or does it make a new reference c to the object and then setting it to null, making it do nothing at all for me?

==

My Cannon class continuously creates instances of the EnemyProjectile class. The EnemyProjectiles class contains a boolean field called "visible". What is the correct way to dispose of my EnemyProjectile class and make it eligible for garbage collection when "visible" is equal to false?

Upvotes: 1

Views: 1442

Answers (1)

scottb
scottb

Reputation: 10084

The joy of using Java, is that memory is managed for you behind the scenes so that, unlike C or C++, you don't have to worry about deconstructing or disposing of objects. When an object is no longer "usable" (as defined by falling out of scope and being unreachable from another active object) then the garbage collector quietly reclaims the space it was occupying.

In Java, you cannot control when objects are garbage collected nor should you try.

Code that depends on a deterministic garbage collection of unused objects will invariably be fragile and difficult to maintain in Java. in part this is because different JVM implementations will garbage collect at different times. System.gc(); is, at best, a suggestion to the JVM that it do garbage collection, but is no guarantee when (or even if) it will happen.

The best thing you can do is design your program so that reference variables have the absolute shortest possible lifespan. Your code is at risk of memory leaks any time a long-lived object retains a reference to a short-lived object (listeners are an example) or when you create data structures that "manage memory" themselves (eg. your own queue or stack implementation).

ArrayList<Cannon> cannonList = Cannon.getCannons();
for (int i = 0; i < cannonList.size(); i++) {
    Cannon c = (Cannon) cannonList.get(i);
    c = null;
}
for (int i = 0; i < cannonList.size(); i++) {
    cannonList.remove(i);
}
System.gc();

In this snippet, there are several issues:

When you use a data structure from the Java Collections API, you should use the interface as the type, not the concrete class. This is by convention, but doing so will keep your code more flexible. Instead of...

ArrayList<Cannon> cannonList = Cannon.getCannons();

write this instead (valid for any class instances that implement the List interface):

List<Cannon> cannonList = Cannon.getCannons();

When possible, you should use the enhanced for-each loop introduced with Java SE 5. It is less error prone. Your for loops should look like this:

for (Cannon c : cannonList) {
    c = null;  // this for loop actually accomplishes no useful work since
               // the reference is null'd as soon as it gets a reference to
               // a Cannon object.  The reference in your ArrayList is unaffected
               // by this assignment
}

cannonList.clear();  // more concise than removing each element from the list.

TL;DR: Garbage collection occurs when it happens. It is non-deterministic. You are never guaranteed when or even if it will happen. Design your Java programs to make your objects eligible for garbage collection at the earliest possible time ... and then don't worry at all about what happens.

Upvotes: 2

Related Questions