Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "unstopped " executed/finished threads

I've got a question about threads. When I do sth like this:

new Thread(new Runnable(){

        @Override
        public void run() {
            //sth to do
        }

    }).start();

What happens when all the code in run() is executed ? Does the system automatically deletes the thread or does the thread still remain in memory?

thx & regards

like image 638
user2224350 Avatar asked Feb 10 '26 21:02

user2224350


2 Answers

When a thread finished its run() method, it will enter the 'dead' state. Then the next thread in your stack runs after.

Dead state :

"A thread is considered dead when its run() method completes. It may still be a viable Thread object, but it is no longer a separate thread of execution. Once a thread is dead, it can never be brought back to life! (The whole "I see dead threads" thing.) If you invoke start() on a dead Thread instance, you'll get a runtime (not compiler) exception. And it probably doesn't take a rocket scientist to tell you that if a thread is dead, it is no longer considered to be alive."

like image 125
renz Avatar answered Feb 12 '26 12:02

renz


Java's Threading Model is a little bit more complicated than that.

Basically, a java.lang.Thread is just a wrapper around some data, not a process by itself. When you call the .start() method, a native thread is created and linked to your java Thread. This work is done by the JVM using internal data structures (JavaThread and OSThread).

Once the .run() method finish, many operations are performed by the JVM to delete the native thread that was used. Therefore, you won't see this thread anymore in you process list (using top or ps, for example).

However, the objects that were allocated in the heap and the java.lang.Thread instance itself stay in memory until a GC cycle collects them.

So, to sum up :

  • Yes, the JVM deletes the native thread that was used

  • No, the JVM does not delete the java.lang.Thread instance that was used

  • The GC will eventually collect this instance

For more information, you should read the book "Java Performance" by Charlie Hunt. It contains lots of information on this topic (and many others).

Hope that helps !

like image 23
Pierre Laporte Avatar answered Feb 12 '26 14:02

Pierre Laporte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!