简体   繁体   中英

Does the runnable class go out of scope when a java thread ends?

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);

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.

mmt被添加到threadList因此只要threadList本身是可访问的并且仍然保留它,就不会对其进行垃圾回收,这在代码示例的最后一行仍然如此,无论您的第一个t (在中间块中)是否仍然保留是否引用它。

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM