Java最终局部变量存储在哪里? [英] Where are Java final local variables stored?

查看:81
本文介绍了Java最终局部变量存储在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下示例:

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

首先, env 存储?是:


  • 由编译器复制到引用它的内部类的隐藏成员变量中

  • 复制到并在堆上引用

  • 在堆栈上留下并以某种方式在那里引用

  • 其他东西

  • 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

我的猜测是第一个选项。

其次,做任何表演这样做会产生的问题(而不是简单地创建 env 作为类的成员变量并引用它),特别是如果要创建大量此类内部类构造引用最终局部变量。

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.

推荐答案

是的,它们被复制,这就是你必须将变量声明为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.

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.

这篇关于Java最终局部变量存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆