javamemory-leaksjava-memory-leaks

Does not storing a newly declared object cause a memory leak?


What I mean to say through the post title is - doing this:

public static void makeNewObjectAndDoTask() {
    new SomeClass().doYourTask();
}

I have myself written such code in languages such Java and JavaScript - declaring a new object without storing it in a variable, JUST to call one of its methods. Does this cause memory leaks? ..or does the object get cleared at the end of the method-stack / gets freed by the Java Garbage Collector?

Should I just be doing this instead - for safety?:

public static void makeNewObjectAndDoTask() {
    SomeClass obj = new SomeClass().doYourTask();
    obj = null;
    //System.gc(); // Perhaps also call the collector manually?
}

Solution

  • As the commentors already answered, there is no memory leak in code like

    public static void makeNewObjectAndDoTask() {
        new SomeClass().doYourTask();
    }
    

    at least in itself, assuming that the SomeClass() constructor and the doYourTask() methods don't create memory leaks.

    Definitely, the garbage collector will clean up the SomeClass instance at some time in the future.

    How does it work?

    The alternative code

    public static void makeNewObjectAndDoTask() {
        SomeClass obj = new SomeClass().doYourTask();
        obj = null;
    }
    

    only delays the garbage collection opportunity, as it stores a reference in obj, thus making the instance accessible for at least a tiny additional period of time, until you assign obj = null;.

    Manually calling the garbage collector as in System.gc(); rarely is a good idea. It forces the GC to run (and to spend execution time on cleaning up memory), instead of relying on the JVM's highly optimized GC scheduling strategies. Don't do it unless you have a thorough understanding of the garbage collector, which led you to the conclusion that the GC strategy fails in your case.

    We don't want OutOfMemoryErrors, and we don't want excessive time wasted for garbage collection, and the standard GC system does a very good job in both aspects.