Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 destroyed?

like image 803
Yevgeny Simkin Avatar asked Feb 25 '11 22:02

Yevgeny Simkin


People also ask

Do Java threads get garbage collected?

No thread (or the things it refers to) will be garbage-collected while it is still running.

How do you clear a thread in Java?

Java Thread destroy() methodThe destroy() method of thread class is used to destroy the thread group and all of its subgroups. The thread group must be empty, indicating that all threads that had been in the thread group have since stopped.

Do we need to close threads in Java?

You do NOT need to call Thread. currentThread(). interrupt() (it will not do anything bad though. It's just that you don't need to.)

Can we reuse threads in Java?

There is no "reuse" in this case. So it is true that you cannot call start() on a Java Thread twice but you can pass as many Runnable as you want to an executor and each Runnable 's run() method shall be called once.


1 Answers

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;
}
like image 152
Tomasz Nurkiewicz Avatar answered Oct 21 '22 17:10

Tomasz Nurkiewicz