Java最终局部变量存储在哪里?

发布于 2024-08-15 20:36:08 字数 488 浏览 6 评论 0原文

举个例子:

public void init() {
    final Environment env = new Environment();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
             env.close();
        }
     });
}

首先,env存储在哪里?是不是:

  • 由编译器复制到引用它的内部类的隐藏成员变量中
  • ,复制到并引用留在堆栈上的
  • ,并以某种方式引用其他东西

我的猜测是第一个选项。

其次,解决由此产生的任何性能问题(而不是简单地创建 env 作为类的成员变量并引用它),特别是当您创建大量此类内部类构造时引用最终局部变量。

Take the following example:

public void init() {
    final Environment env = new Environment();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
             env.close();
        }
     });
}

Firstly, where is env stored? Is it:

  • copied by the compiler into a hidden member variable of the inner class that references it
  • copied to, and referenced on, the heap
  • left on the stack and somehow referenced there
  • something else

My guess is the first option.

Secondly, do any performance issues that arise from doing this (rather than simply creating env as a member variable of the class and referencing it as such) particularly if you are creating large numbers of such inner class constructs that reference final local variables.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苦笑流年记忆 2024-08-22 20:36:08

是的,它们被复制,这就是为什么你必须将变量声明为final。这样,就可以保证它们在复制后不会改变。

这对于实例字段来说是不同的,即使不是最终的,也是可以访问的。在这种情况下,内部类获取对其用于此目的的外部实例的引用。

private Environment env;  // a field does not have to be final

public void init() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
             env.close();
        }
     });
}

其次,这样做会产生任何性能问题吗?

与什么相比?您需要有字段或变量才能让您的内部类工作,而副本是一种非常有效的方法。无论如何,它只是一个“浅”副本:仅复制对(在您的示例中)环境的引用,而不是环境本身。

Yes, they are copied, which is why you have to declare the variable as final. This way, they are guaranteed to not change after the copy has been made.

This is different for instance fields, which are accessible even if not final. In this case, the inner class gets a reference to the outer instance that it uses for this purpose.

private Environment env;  // a field does not have to be final

public void init() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
             env.close();
        }
     });
}

Secondly, do any performance issues that arise from doing this?

Compared to what? You need to have the field or variable around for your inner class to work, and a copy is a very efficient way. It is only a "shallow" copy anyway: just the reference to the (in your example) Environment is copied, not the Environment itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文