-1

In the scenario below how what happens with regards to GC? I'm pretty sure the reference to "a" will not actually get returned, hence no need to worry about leaving this reference in scope. So pretty much the return of "a" never actually takes place and therefore goes out of scope and only "b" is ever returned?

Object testFinally(){
    try {
        Object a = new Object();
        return a;
    } finally {
        Object b = new Object();
        return b;
    }
}

void callToTestFinally(){
   Object v = testFinally();
}
newlogic
  • 807
  • 8
  • 25
  • How is this abuse of `finally` related to GC? – Kayaman Dec 07 '16 at 18:22
  • Does reference "a" get returned to the callers scope or is it never returned and therefore the "return a" is just ignored? – newlogic Dec 07 '16 at 20:42
  • How would it be returned? You have 2 return statements, but you know the method can only return one value. – Kayaman Dec 07 '16 at 20:51
  • I'm just making sure, hence the question. Practically, you wouldn't expect x++ to run at all within return x++, when there is a finally return x, but it does, so I'm just making sure. – newlogic Dec 07 '16 at 21:13
  • I *would* expect `x++` to be run, since `return x++;` consists of two (well, more than two, but let's keep it simple) steps. Incrementing x, then returning its value. The `return a;` isn't *ignored*, it's just that after it has been executed, it's overridden by `return b;` in the finally block, making the original return value disappear. – Kayaman Dec 07 '16 at 21:22
  • The only complicated point is the question what really gets returned. You can try it out or read the JLS or google for an answer on SO. I'm pretty sure, that all three ways work. What you get the answer, then everything gets clear.... so how is that related to the GC? – maaartinus Dec 11 '16 at 21:56

1 Answers1

1

Same procedure as always. If an instance is no longer reachable by a strong refererence, it will be eligible for garbage collection. Nothing different for your a and finally, it goes out of scope and can be collected.

k5_
  • 5,450
  • 2
  • 19
  • 27