Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cleanup a Thread after its run method finishes?

Tags:

What should be done with a Thread after its run() method finishes executing? Is there any cleanup needed for a Thread in Java?

like image 999
nath Avatar asked Nov 26 '10 07:11

nath


People also ask

How do you clean up a thread?

We have found that just washing them or giving them a scrub with pipe cleaners is not sufficient to remove things like rust, burnt oil and grime. The only way to really clean the threads is to run a thread chaser or very carefully a thread cutting tap.

What happens to thread pool after it finishes its task?

Once a thread in the thread pool completes its task, it's returned to a queue of waiting threads. From this moment it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. There is only one thread pool per process.

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.

When a process is terminated what happens to its thread?

The Terminated property is set from a different thread to signal to the worker thread that it should terminate. It's then up to the worker thread to obey the signal by checking the Terminated flag in the Execute procedure. After the Execute procedure is finished, the Thread's Finished property is automatically set.


1 Answers

Unless the thread's work has used some unmanaged resources (network streams, files etc) - in which case it should clean up after itself - there's nothing you need to do.

Note that holding a reference to the Thread object representing the thread won't keep the underlying OS thread alive.

like image 79
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet