How good a practice is this?

Say I have a Java application which handles thousands of users. So for each user action a certain block of code will be executed repeatedly and I am creating millions of temporary objects. I write my method this way.

public void myMethod(ClassB a, ClassA b) {
    ClassC c = null;
    ClassD d = null;

    try {
        c = new ClassC();
        d = new ClassD();

        // Some code which uses a, b, c, d.
    } catch (Exception e) {
    } finally {
        a = null;
        b = null;
        if (c != null) {
            c = null;
        }
        if (d != null) {
            d = null;
        }
    }
}

Classes can be of any type. (Primitives, Lists or Maps) I would use clear() or reset() functions if available.

Is this really helpful for GC or should I let Java handle this on it's own?

Jon Skeet
people
quotationmark

You should absolutely let Java handle this on its own. All you're doing is making your code harder to read and maintain. All the variables you're nulling out are going out of scope at the end of the method anyway - and the GC knows that.

Oh, and in general you shouldn't catch Exception... catch specific exceptions (if you can actually handle them).

people

See more on this question at Stackoverflow