Alex Rivera | Logout

Does a running thread in an object prevent it from being garbage collected in java?

Asked 2009-01-26T17:15:50.560
10

Given the code:

 new Thread(new BackgroundWorker()).start();

Intuitively it feels like the BackgroundWorker instance should be safe from GC until the thread exits, but is this the case ? And why ?

Edit:

All this heat is basically generated by me asking at least two different questions in the same post. The question in the title has one answer, the code sample leads in a different direction - with two possible outcomes depending on inlining.

The answers posted are really excellent. I will be awarding Software Monkey the green checkbox. Please note that Darron's answer is equally valid, but Software Monkey explained the problem I was having; it was the answer that worked for me.

Thank you all for making this a memorable affair ;)

Edit
Report

1 Answer

1

I am willing to bet that the JVM includes a reference to each thread object that is active or can be scheduled in its root set, but I don't have the spec with me to confirm this.

answered 2009-01-26T17:23:54.693

Your Answer