开发者

Do Java Threads need any cleanup?

I see that all the stop and destroy and anything else that deals with cleanup methods have been deprecated.

If I have a new Thread() or a class that extends Thread running, do I need to do anything in its run() method other than let it get to the end of regular execution? Or is there a background mechanism that understands that the Thread has run through all its tasks and can be d开发者_运维知识库estroyed?


When you call start() on your thread, native mechanism in JVM close to the operating system are starting your thread, eventually executing run(). When run() finishes, JVM takes care of everything.

You might be concerned about garbage collection or other resources cleanup. Of course if you open file/network connection inside a thread, it must be closed like everywhere else. Also the garbage collector, while analyzing live objects, takes into account objects referred from running threads. But the moment thread finishes, all the objects referenced by it (or by Runnable implementation passed to the thread) are eligible for garbage collection.

quick&dirty edit for exit method of Thread, as visible contextClassLoader is missing x.x

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


No cleanup needed. Once it finishes its task, the jvm will kill it.


The stop() method actually causes the Thread to throw an Error or Exception. The reason it is deprecated is this can happen anywhere in the code anything it modifies in a potentially unknown state. stop() is only really safe when stopping the current thread because you know when it will happen. BTW, You can catch the Error/Exception which would mean the Thread does not stop().

In any case, the result is the same, the run() returns (or fails to catch an Exception/Error). The stop() method triggers a special Error called ThreadDeath. The only thing special about it is that normally, an uncaught exception/error is printed, but this one is not. (And it doesn't have Error at the end of its name ;) You can change this behaviour if you wish.

When the Thread is no longer referenced, it can be cleaned up. (just like any other object) Note: you can hold a reference to it in another thread, preventing it from being cleaned up even thought it has finished.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜