Luke Taylor
Luke Taylor

Reputation: 9599

Java: Creating new instances

Say I want to create a new instance foo.

I'll do it like this:

SomeClass foo = new SomeClass();

Now lets say the object has reached its end (eg. like a colliding bullet in a game) and should be disposed and reinitialized. To reset the object I could either do this:

foo = new SomeClass();

or this

foo.reset();

NB: The reset() method would just reset all the variables from that instance.

Which is the better way to go (when trying to avoid GC)? Would the first option create a new pointer?

Upvotes: 1

Views: 1234

Answers (2)

caoxudong
caoxudong

Reputation: 373

If you want to avoid GC, the second option is better.

Actually, even if you choose the first option, JVM would not do GC immediately. It will GC when heap is full(or not enough for the objects just created). The first one creates a new instance, and there is no strong reference to the old object. So when JVM's heap is full, it will do GC, and the old object will GCed.

Besides, there's also some content about GC and reference is the kind of the reference you used. There're four kind of refrences, named "Strong, Soft, Weak, and Phantom". Even if you use the second option, the object "foo" may also be GCed, unless the reference to the object "foo" is a strong refrence. See JDK document to get more about the four reference type, such as Reference Phantom SoftReference WeakReference

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

The first option creates a new object and leaves the old one to be collected as garbage (unless there are other live references to it).

One strategy for reducing GC is to maintain an object pool. This would be just a collection of objects that have no current use and are available for reuse. When you are finished with an object, call a method that returns it to the pool. When you need a fresh object, call a method that checks the pool before creating a new object; if the pool is not empty, it would remove an object from the pool and reuse that rather than creating a new object.

public class SomeClass {
    private static final int MAX_POOL_SIZE = . . .;
    private static final ArrayList<SomeClass> pool = new ArrayList<SomeClass>();

    public static SomeClass getInstance() {
        int poolSize = pool.size();
        if (poolSize > 0) {
            return pool.remove(poolSize-1);
        }
        return new SomeClass();
    }

    public void recycle() {
        // reset any fields
        if (pool.size() < MAX_POOL_SIZE) {
            pool.add(this);
        }
    }
    . . .
}

When you need a new SomeClass, call SomeClass.getInstance(). When you are done with an instance, call it's recycle() method.

Upvotes: 2

Related Questions