在 Java 中,在多次调用的非静态方法中将局部变量设置为 final 会导致内存泄漏吗?

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

例如假设我们有:

    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...
    }

这种情况下会发生内存泄漏吗?

我只是不明白 final 局部变量的真正含义。这是否仅仅意味着不能重新分配局部变量,仅此而已?最终声明它是否将它放在 java heap/memory 中的某处,这样它就像一个实例变量但带有 different/unique?特别是因为 inner/nested class 可以使用最终局部变量,但不能使用非最终局部变量?

没有。如果没有 final 就没有内存泄漏,那么 final 就不会发生内存泄漏。

只有 final 对局部变量所做的事情(在Java 8 中)1 是防止您多次分配给变量。

1 在 Java 7 和更早的版本中,还有另一个与内存泄漏无关的影响。

难道仅仅意味着局部变量不能被重新赋值,仅此而已?

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

最终声明它是否将它放在 java heap/memory 中的某处,这样它就像一个实例变量但带有 different/unique?

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

特别是因为 inner/nested class 可以使用最终局部变量,但不能使用非最终局部变量?

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.