退出块代码后符合 GC 条件的变量

Variables eligible for GC after exit from block-code

假设我有这样的代码:

public static void someMethod(){
    
    int sum = 0;
    {

        int a = 3;
        int b = 4;
        sum = a + b;

    }

    //a and b is not visible here
    //but a and b will be eligible for GC?

    //more code

}

我的问题是 ab 在从该块执行退出后或仅在 someMethod 完成后是否符合 GC 条件。

理论上,任何局部变量一旦超出范围就不再是 GC 根。 (即使 non-local 通过嵌套 class 等访问变量。在这种情况下,变量中的值将复制到另一个具有更长生命周期的(合成)变量中。)

实际上,JVM 实际上可能会等到封闭方法调用 returns。它取决于实现。

但这是你的例子:

  1. 那些局部变量可以被 JIT 编译器优化掉。
  2. 它们是原始变量,所以它们不包含对对象的引用。 GC 不会关注它们。

一般来说,您通常不会为此担心。 很少 重要的是一些变量变得不可访问的时间晚于绝对必要的时间。

但是请考虑以下几点:

public static void longRunningMethod() {
    // do stuff
    {
       Map<X, Y> bigMap = ... // create and populate a huge map
       // use bigMap
       bigMap = null;
    }
    // long running computation
}

如果您有明确证据表明 bigMap 存在“垃圾保留”问题,您可能 考虑将其分配给 null,如上所述。另一方面,该作业也可能被优化掉!