Question

Say that (possible on a separate thread) I am running some method ClassA.foobar(). Inside that method is a try, (possibly catch), finally block.

Now if the last reference to this ClassA object (or to this thread) is lost when execution is still in the middle of the try-block (or the catch-block), could this object(/thread) get garbage collected before I get to the finally block? In other words: is the finally block still guaranteed to run even if there are no strong references to the object(/thread) left in memory?

(I don't know how the GC handles orphaned live threads.)

Dummy example:

[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!
            }
        }
    }
}
Was it helpful?

Solution

In other words: is the finally block still guaranteed to run even if there are no strong references to the object(/thread) left in memory?

Yes. finally blocks don't get skipped like that - nor does any other code.

Execution threads aren't objects in the garbage collection sense. It's important to distinguish between the thread itself and the java.lang.Thread object representing it - although I don't think the Thread object would be garbage collected before the thread terminates either.

In particular, it's entirely possible to have threads where there are no references to the runnable or anything else still in the system, and the thread can keep going. For example:

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

After the thread has started, the calling code has no reference to the instance of the anonymous class created, or the Thread object - but it will still print all 1000 numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top