Will an unused object used in an instance of an anonymous class not expire?

Assume this code:

public class Foo { public static Thread thread; public String thing = "Thing!!"; public static void main(String[] args) { new Foo().makeThread(); // <- Foo object may get garbage collected here. thread.start(); } private void makeThread() { thread = new Thread(new Runnable() { @Override public void run() { // !! What if the instance of Foo is long gone? System.out.println(thing); } }); } } 

Here, the temporary object new Foo() creates a statically stored Thread thread that uses the String thing associated with the instance in the anonymous Runnable implementation. Does the String thing collect garbage collected after the expiration of new Foo() , or will it be stored for use within run() ? Why?

+5
source share
2 answers

The string will not be garbage collected until the thread is set to null or some other thread , because there is a chain of links leading to the object from the static variable.

The link chain looks like this:

static thread implicitly refers to the instance of Foo from which it was created through an instance of an anonymous class derived from Runnable . In turn, the Foo instance contains a reference to the thing , making sure that the object does not receive garbage collection.

What if the instance of Foo is long gone?

Foo not going anywhere, because it is stored live by implicit link from the thread object.

Note. . This answer intentionally ignores the effect of interning String objects created from string literals.

+10
source

An anonymous inner class will refer to Foo as how it is going to access the thing . As if you had:

 public class FooRunnable implements Runnable { private final Foo foo; public FooRunnable(Foo foo) { this.foo = foo; } public void run() { System.out.println(foo.thing); } } 

Then:

 private void makeThread() { thread = new Thread(new FooRunnable(this)); } 

So basically, while the new thread supports the Runnable implementation instance, which in turn prevents the Foo instance from being collected.

+11
source

All Articles