0

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?

Ben
  • 193
  • 1
  • 11
  • 1
    Short answer "No". Keyword `final` in the context means only that you *can't change* the reference any more, say write `foo = new Foo(someArgs);` however the reference itself can be collected by GC like any non final reference. – Dmitry Bychenko Apr 29 '15 at 07:28

2 Answers2

3

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • Not only in Java 8. `final` has worked this way since its introduction in the language. – fge Apr 29 '15 at 07:23
  • @fge Before Java 8 you couldn't use non-final variables across anonymous class boundaries. Now it's been relaxed so that you can't use a variable that's assigned more than once (not "effectively `final`") across an anonymous class boundary. – user253751 Apr 29 '15 at 07:25
1

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.

Mohan Raj
  • 1,104
  • 9
  • 17