Java Multi-Threading Two thread instances are the same thread object

I am confused with a 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 this mean that testThread and m_logTestThread are different instances, but point to the same object in memory, so they are the same thread?

If so, what is the purpose of if (testThread != null) ?

+4
source share
2 answers

Does this mean that testThread and m_logTestThread are different instances but point to the same object in memory, so they are the same thread?

This is partly true. In fact, testThread and m_logTestThread are two different references not instances . And both links point to the same Thread object. So, just pointing reference m_logTestThread to null does not make the reference testThread also a reference to null .

You can also see this in practice with a simple example: -

 String str = "abc"; String strCopy = str; // strCopy now points to "abc" str = null; // Nullify the `str` reference System.out.println(strCopy.length()); // Will print 3, as strCopy still points to "abc" 

That way, even if you set one of the links to zero, the other link still points to the same Thread object. An object does not have the right to garbage collection until it points to 0 reference or circular reference .

See this link: Circular Link - The wiki page to find out exactly what Circular Refeference .

what is the purpose of "if (testThread! = null)"?

Simple You can infer from the condition that it checks if the testThread reference testThread to a null object. null check is done so that you do not get the NPE inside the if-construct , where you are trying to abort the Thread pointed to by this link. Therefore, if this link points to null , then you do not have a thread associated with this interrupt link.

+3
source

Does this mean that testThread and m_logTestThread are different instances, but point to the same object in memory, so they are the same thread?

testThread and m_logTestThread are two links pointing to the same instance of the Thread object. (say T)

 Thread testThread = m_logTestThread; 

This line means that testThread will start pointing to the same object where m_logTestThread is m_logTestThread . that is, both point to T.

 m_logTestThread = null; 

This line means that m_logTestThread will begin to point to null , that is, it will no longer point to T. But it does not change testThread , and testThread still points to T.

what is the purpose of "if (testThread! = null)"?

since testThread may OR not be null , therefore this condition is used for further calculation before using testThread .

0
source

Source: https://habr.com/ru/post/1446148/


All Articles