Dave
Dave

Reputation: 7603

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();

Upvotes: 17

Views: 10053

Answers (3)

bragboy
bragboy

Reputation: 35552

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

Upvotes: 10

gustafc
gustafc

Reputation: 28875

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.

Upvotes: 12

Mike Baranczak
Mike Baranczak

Reputation: 8374

Spawning a new thread is a pretty expensive process. What you want is a thread pool. There are different ways to go about that - here's one.

Upvotes: 2

Related Questions