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.