views:

111

answers:

3

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();
+4  A: 

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.

Bragboy
... unless some other "live" data structure maintains a reference to the thread object. With the example posed in the OP that wouldn't be a problem.
Pointy
... but that is a pattern than occurs when you want to `join()` the threads, say, to retrieve some results from the `Runnable`, but again, you can't do that in your example since the `Runnable` reference is lost.
Fly
A: 

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.

Mike Baranczak
Spawning threads *was* expensive in *nix systems (*namely Linux*) a long time ago, but in kernel 2.4 (*or was it 2.6?*) they changed their threading system so that spawning new threads is now practically free. Note that in Windows environments spawning threads has always been quite cheap. That said, using thread pools is a smart thing, because there's naturally always some overhead and you rarely really need to have a billion running threads when about a dozen would do.
Esko
+2  A: 

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.

gustafc