gpt4 book ai didi

java - 变量在 catch block 后立即被垃圾收集

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:06 24 4
gpt4 key购买 nike

我可以从垃圾收集器中看到这种奇怪的行为

public class A {
public static void main(String[] args) {

String foo;
try {
foo = "bar";

int yoo = 5; //1
} catch (Exception e) {
}

int foobar = 3;//2
}
}

如果我去调试并在//1 foo 不是 null 并且它的值为“bar”但在断点处放置断点//2 foo 是 null,这在调试时可能很难理解。我的问题是是否有任何规范说明这是垃圾收集器的合法行为

有了这个小变化,它就不会收集垃圾:

public class A {
public static void main(String[] args) {

String foo;
try {
foo = "bar";
} catch (Exception e) {
throw new RuntimeException(e);
}

int foobar = 3;
}
}

为什么?

最佳答案

在这种情况下,您在设置 foo 变量后不使用它,因此 JVM 完全忽略该变量甚至是合法的,因为它从未使用过并且不会改变程序的结果。

然而,这在 Debug模式下不太可能发生。

在您的情况下,只要 foo 在范围内或者您持有对它的引用(包括 try/catch block 之后的部分),它就不应该被 GC。

编辑

实际上,我得到的行为与您在使用 Java 7.0_03 的 Netbeans 7.1.1 中描述的行为相同...

一个问题可能是因为您没有为 foo 设置默认值,所以您不能在 try/catch block 之后使用它(它不会编译)。

字节码

  • 使用您使用的代码
public static void main(java.lang.String[]);
Code:
0: ldc #2 // String bar
2: astore_1
3: iconst_5
4: istore_2
5: goto 9
8: astore_2
9: iconst_3
10: istore_2
11: return
  • 使用 String foo = null; 作为第一条语句,在这种情况下,调试器会在 try/catch block 之后看到值:
public static void main(java.lang.String[]);
Code:
0: aconst_null
1: astore_1
2: ldc #2 // String bar
4: astore_1
5: iconst_5
6: istore_2
7: goto 11
10: astore_2
11: iconst_3
12: istore_2
13: return

我不是字节码专家,但他们看起来和我很相似......

结论

我个人的结论是,要让调试器显示 foo 的值,它必须运行某种类型的 foo.toString(),这不是作为 foo 的 catch block 之后的有效语句可能尚未初始化。在该部分添加 System.out.println(foo) 是不合法的(不编译)。调试器有点迷失了值是什么,并显示 null

为了说服自己这与 GC 无关,您可以尝试以下示例:

public static void main(String[] args){
String foo;
char[] c = null;
try {
foo = "bar";
c = foo.toCharArray();

int yoo = 5; //1
} catch (Exception e) {
}

int foobar = 3;//2
}

foobar 行中,您可以看到 c 包含 bar 但 foo 显示为 null。所以字符串仍然存在,但调试器无法显示它。

更有趣的例子:

public static void main(String[] args){
String foo;
List<String> list = new ArrayList<String>();

try {
foo = "bar";
list.add(foo);
int yoo = 5; //1
} catch (Exception e) {
}

int foobar = 3;//2

}

foobar 行,foo 显示为 null,但 list 包含 "bar"... 不错。

关于java - 变量在 catch block 后立即被垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com