Suppose I create an instance of this Test class, which starts a new Thread using a nested class :
public class Test
{
private String _str;
public Test()
{
_str = "Hello world !";
new TestThread().start(); // Start a background thread
}
private class TestThread extends Thread
{
public void run()
{
while (true)
{
System.out.println(_str);
Thread.sleep(1000);
}
}
}
}
What happens now if I remove any strong references to my Test instance ? The background thread will still be alive and will continue to print the _str variable, but I’m afraid that the GC can collect it anytime.
Of course I can create a local copy of the reference (with a constructor : public TestThread(String str) and store it in a local variable) but I wonder if this is necessary.
TestThreaditself has a strong reference toTest, so as long as it is not collectable, the instance ofTestwon’t be collectable. Since it’s a running thread, the instance ofTestThreadobviously isn’t available for collection.When you create a non-static inner class (TestThread), every instance of that class has an implicit reference to an instance of its enclosing class (Test).
See the Inner Classes section of the Nested Classes Java Tutorial.
You don’t have to be “afraid” of what the GC might do. It won’t collect an object that you could possibly reference, unless you’re going out of your way to work with weak references.