Nothing.
The variable r
is not the MyRunnable
object itself; it's merely a reference to that object within your block of code.
Initially you create a new MyRunnable
object. And then, you "give it the name"/assign it to the variable r
. You then pass it into the Thread
constructor (using the variable to describe which object you're talking about). Within that constructor, it will almost certainly be assigned to other references (in the JDK I'm using, it's a field called target
).
Later on, you repoint your reference r
at another object - in this case, the null
object. This does not have any effect on the object it used to point it, just the reference. Likewise it does not have any effect on other references pointing to the same object.
So the Thread.target
reference still points at the same MyRunnable
object you initially created, and from the thread's viewpoint, nothing has changed.
The only potential difference is that your (outer) code snippet no longer has a reference to the object it created. So the code that follows will not be able to call any methods on that object, or pass it as a method argument etc. (This shouldn't be a problem - or surprising - given that you deliberately nullified your only reference to that object!)
If nothing holds a reference to a particular object, then the garbage collector will on its next run consider that object unreachable, and collect it. This is seldom something you need to worry about though, since if you don't have a reference to the object you wouldn't be able to do anything with it anyway (the whole principle behind GC).
In this case, the MyRunnable
won't be GCed because the Thread
still holds a reference to it.
That said, if the constructor were to behave differently and not store a reference because it didn't need one (maybe it just uses the toString()
representation), then the object would be deemed unreachable, and would be collected. In both cases the garbage collector would do the right thing - collecting an object if and only if nothing refers to it any more - without you needing to worry or know about that in your code.