Search code examples
javamemory-leaksfinal

In Java can making a local variable final in a non-static method that is called many times cause a memory leak?


For example lets say we have:

    public void doThis() {
        final Foo foo = Foo.getInstance();
        ... initialize foo somehow...
        baz(Bar.getInstance(foo)); // adds Bar instance to something
        ... bar will be popped from some list, used, and disposed of...
    }

Can a memory leak occur for this scenario?

I'm just not understanding what a final local variable really means. Does it just mean that the local variable cannot be reassigned, and that is it? Does declaring it final put it somewhere in the java heap/memory such that it's like an instance variable but with a different/unique? Especially since an inner/nested class can use a final local variable, but not a non-final local variable?


Solution

  • No. If there wasn't a memory leak without final, then there won't be one with final.

    The only thing that final does to a local variable (in Java 8)1 is prevent you from assigning to the variable more than once.

    1 In Java 7 and earlier, there was another effect which also had nothing to do with memory leaks.