【发布时间】:2013-11-04 06:40:06
【问题描述】:
说(可能在单独的线程上)我正在运行一些方法 ClassA.foobar()。 该方法内部是一个 try, (可能是 catch), finally 块。
现在,如果在执行仍在 try 块(或 catch 块)中间时丢失了对该 ClassA 对象(或该线程)的最后引用,该对象(/线程)是否可以被垃圾回收?在我到达finally块之前?换句话说:即使内存中没有对对象(/线程)的强引用,finally 块是否仍然保证运行?
(我不知道 GC 是如何处理孤立的活动线程的。)
虚拟示例:
[Some context]
{
ClassA classA = new ClassA();
//Point is this instance and a reference to it exists
class ClassA
{
public void foobar()
{
try
{
classA = null;
//Point is that the last reference to this instance is lost,
//and that this happens at this point in foobar() execution.
//The actual location of this line of code is irrelevant.
}
finally
{
//some important stuff here!
}
}
}
}
【问题讨论】:
-
但最后一个引用没有丢失——
this仍然存在并指向该对象。而且,this引用绝对可以从 GC 根(即线程)访问,因为它位于线程的堆栈帧上。换句话说,没有所谓的“孤立的活动线程”这样的东西,因为线程本身就是阻止某些东西被 GC 的东西(特别是,如果一个线程知道该对象)。所以,简而言之不是:finally块总是被调用。 -
为了完整起见,我想在一个类似的问题上添加一个链接到此评论,我发现该问题提供了丰富的信息:link(它提到了 finally 块不运行的贬低案例。)
-
是的,如果您调用
System.exit或强制终止Java 进程(例如,在Linux 上使用kill -9),它也不会运行。
标签: java garbage-collection thread-safety try-catch-finally finally