Java GC是否可以收集实例,而方法则使用它

Ily*_*dov 4 java garbage-collection

我有一个关于Java GC的简单问题.一些例子:

Object instance = new Object();
longMethod(instance);

...

// First example
private void longMethod(Object arg) {
   Thread.sleep(1000 * 60 * 60)
   // this method works 1hr. Does it keep reference to Object and GC canot release it?
}

//Seconde example
private void longMethod(Object arg) {
  arg = null;
  Thread.sleep(1000 * 60 * 60)
  // we clear reference in method. Can GC relese Object now?
}
Run Code Online (Sandbox Code Playgroud)

那么两种情况下"实例"的生命周期是什么?谢谢.

Era*_*ran 5

在这两种情况下Object instance,它都是调用方法的局部变量,它longMethod保存对实例的引用,因此GC在调用的方法longMethod结束之前无法释放它.

请注意,arg = null仅将本地引用设置longMethod为null.它不会更改instance调用方法中变量的值longMethod.