Reputation: 8805
If I create an object that implements Runnable, and I start a thread with it...
ArrayList<Thread> threadlist = new ArrayList<Thread>();
{
MergeThread mmt = new MergeThread();
Thread t = new Thread(mmt);
threadlist.add(mmt);
t.start();
}
t.join();
Thread t = threadlist.get(0);
At this point is mmt guaranteed to exist or could it have gone away if garbage collection got it.
What I am asking is if the Thread object holds on to the Runnable class after the thread has ended.
edit: there's a mistake in the above it should say threadlist.add(t);
Upvotes: 1
Views: 864
Reputation: 15699
From the source of the Thread
class:
/**
* This method is called by the system to give a Thread
* a chance to clean up before it actually exits.
*/
private void exit() {
if (group != null) {
group.remove(this);
group = null;
}
/* Aggressively null out all reference fields: see bug 4006245 */
target = null;
/* Speed the release of some of these resources */
threadLocals = null;
inheritableThreadLocals = null;
inheritedAccessControlContext = null;
blocker = null;
uncaughtExceptionHandler = null;
}
So the system calls Thread#exit()
and the reference to target
(which is a runnable the thread is running) is released.
There is also a bug report #4006245 on bugs.sun.com that refers to clearing the target
reference.
Upvotes: 3
Reputation: 328618
mmt
is added to threadList
so it will not be garbage collected as long as threadList
itself is reachable and still holds it, which is still the case on the last line of your code example, whether your first t
(in the middle block) still holds a reference to it or not.
Upvotes: 2
Reputation: 421020
The code you posted is not really clear to me. However, regarding
At this point is mmt guaranteed to exist or could it have gone away if garbage collection got it.
I can say the following: If you can still get hold of it, the garbage collector won't reclaim the object (and if you can't get hold of it, there's no point in worrying if the object has been GC'd or not).
Upvotes: 1