Java最终局部变量存储在哪里?
举个例子:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它们被复制,这就是为什么你必须将变量声明为final。这样,就可以保证它们在复制后不会改变。
这对于实例字段来说是不同的,即使不是最终的,也是可以访问的。在这种情况下,内部类获取对其用于此目的的外部实例的引用。
与什么相比?您需要有字段或变量才能让您的内部类工作,而副本是一种非常有效的方法。无论如何,它只是一个“浅”副本:仅复制对(在您的示例中)环境的引用,而不是环境本身。
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.
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.