I am confused with the snippet from this code:
void stopTestThread() {
// thread should cooperatively shutdown on the next iteration, because field is now null
Thread testThread = m_logTestThread;
m_logTestThread = null;
if (testThread != null) {
testThread.interrupt();
try {testThread.join();} catch (InterruptedException e) {}
}
}
Does that mean testThread and m_logTestThread are different instances but point to the same object in the memory, so they are the same thread?
If so, what the purpose is of if (testThread != null) ?
This is partially true. Actually
testThreadandm_logTestThreadare two differentreferencesnotinstances. And both the reference are pointing to the sameThreadobject. So, just making areferencem_logTestThreadpoint tonulldoes not make thetestThreadreference also point tonull.You can also see it in practice by a simple example: –
So, even if you set one of the reference to null, the other reference still points to the same Thread object. An object is not eligible for Garbage Collection until it has
0 referencepointing to it, or there is acircular reference.See this link: – Circular Reference – wiki page to know what exactly is
Circular Refeference.Its simple. You can infer from the condition that, it is checking whether the
testThreadreference is pointing to anullobject.The
null checkis done so that, you don’t get aNPEinside theif-construct, where you are trying to interrupt the Thread pointed to by that reference. So if that reference is pointing tonull, then you don’t have any thread associated with that reference to interrupt.