由于GC处于线程状态,最终会阻止跳过吗?

Ano*_*ken 4 java garbage-collection finally thread-safety try-catch-finally

说(可能在一个单独的线程上)我正在运行一些方法ClassA.foobar().在这个方法里面是一个尝试,(可能是捕获),最后阻止.

现在,如果执行仍在try-block(或catch-block)中间时,对此ClassA对象(或此线程)的最后一次引用会丢失,那么此对象(/ thread)是否可以在我获取之前进行垃圾回收到了最后一块?换句话说:即使没有对内存中剩余的对象(/ thread)的强引用,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!
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

换句话说:即使没有对内存中剩余的对象(/ thread)的强引用,finally块仍然可以保证运行吗?

是.finally块不会像这样被跳过 - 也没有任何其他代码.

执行线程不是垃圾收集意义上的对象.区分线程本身和java.lang.Thread表示它的对象很重要 - 尽管我认为Thread在线程终止之前对象不会被垃圾收集.

特别是,完全有可能让线程没有对runnable或系统中任何其他内容的引用,并且线程可以继续运行.例如:

new Thread(new Runnable() {
    @Override public void run() {
        for (int i = 0; i < 1000; i++) {
             System.out.println(i);
        }
    }
}).start();
Run Code Online (Sandbox Code Playgroud)

线程启动后,调用代码没有引用创建的匿名类的实例或Thread对象 - 但它仍然会打印所有1000个数字.