简体   繁体   中英

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?

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.

Does it just mean that the local variable cannot be reassigned, and that is it?

Yes it means it behaves like constant variable where further reassignment or modification could not done.

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?

Final is identifier. This is another variable gets allocated in the java heap. No special memory location available for the Final variable.

Especially since an inner/nested class can use a final local variable, but not a non-final local variable?

Inner class can access the outer class variable and but it cannot use local variable unless it is declared as Final. Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM