Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do java threads get deleted when they finish

Say I spawn a thread every couple seconds using the method below and every thread takes about a second to complete. Do the finished threads get deleted?

new Thread (new myRunnableClass()).start();
like image 448
Dave Avatar asked Sep 28 '10 04:09

Dave


2 Answers

The native, OS-level thread is released as soon as the thread finishes (circa when run() finishes), but the thread object lives, like any other object, until it becomes unreachable and the garbage collector feels like running.

Edit: It might also be interesting to know that Thread (in Sun's Oracle's implementation, anywho) has a private method called by the VM when the thread exits, which aggressively nulls several fields, including the one referring to the Runnable set by the Thread(Runnable) constructor. So even if you retain a reference to the Thread, the things it doesn't need after finishing execution will be released, regardless.

like image 64
gustafc Avatar answered Oct 04 '22 02:10

gustafc


I would not call it deleted. Once the thread completes, it will go to dead state getting ready to be garbage collected by the JVM.

enter image description here

like image 37
bragboy Avatar answered Oct 04 '22 01:10

bragboy