Nothing.
The variable r is not a MyRunnable ; this is just a reference to this object in your code block.
First you create a new MyRunnable . And then you βgive it a nameβ / assign it to the variable r . Then you pass it to the Thread constructor (using a variable to describe which object you are talking to). Inside this constructor, it will almost certainly be assigned to other links (in the JDK I use, this is a field called target ).
You later reassign the r link to another object β in this case, the null object. This does not affect the object that he used to indicate, just a link. Similarly, this does not affect other links pointing to the same object.
So, the Thread.target link still points to the same MyRunnable that you originally created, and nothing has changed from the point of view of the thread.
The only potential difference is that your (external) piece of code no longer has a link to the object it created. Thus, the following code will not be able to call any methods for this object or pass it as a method argument, etc. (This should not be a problem - or a surprise - given that you intentionally canceled your only link to this object!)
If nothing refers to any particular object, the garbage collector in the next run considers that this object is unavailable and collects it. This is rarely something you need to worry about, because if you donβt have a reference to the object, you still canβt do anything with it (the whole principle is for the GC).
In this case, MyRunnable will not be GCed, because Thread still contains a link to it.
However, if the constructor should behave differently and not store the link because it is not needed (maybe it just uses the toString() view), then the object will be considered unreachable and will be assembled. In both cases, the garbage collector will do the right thing β collect the object if and only if nothing refers to it β without having to worry or know about it in your code.
Andrzej doyle
source share