The Thread
class is a proxy for the real thread which is in native memory.
I hope my assumption is correct that once thread finishes its run() method it becomes eligible for garbage collection.
There is actually a bit of code after run(), this code handles uncaught exceptions.
Once the thread dies its native memory and stack are freed immediately without needing a GC. However, the Thread
object is like any other object and it lives until it is GC has decided it can be free e.g. there is no strong reference to it.
Similarly, a FileOutputStream is a proxy for a file in the operating system. You can still have a reference to the object even after the file has been close()
or even deleted.
If it doesn't become eligible for garbage collection after returning from run(), should one set its reference to null to do that?
You rarely need to do this anywhere. In fact it is often simpler not keep a reference to the thread in the first place, or to use an ExecutorService to manage your threads.
When I have an object which has a Thread
field I often have this object die when the thread dies, thus the field doesn't need to be null
ed out.
I also use the built in thread pool used for Fork/Join. This is a more light weight way to perform tasks in a background thread as it doesn't create and destroy threads so much.
ExecutorService fjp = ForkJoinPool.commonPool();
Being eligible for garbage collection doesn't necessarily mean that the object will be removed from memory. It is at the sole discretion of the underlying operating system / JVM when it is garbage collected. But how can one make sure (either through a Java program or external tool) that the object is completely removed from the memory?
You can't and generally shouldn't try. The GC will clean up resources when it needs to.
If a thread is said to be dead once it finishes its run() method, why can I still be able to execute isAlive() or getState() on the same thread object? Both the calls return false and RUNNABLE respectively.
The thread object is like any other object. You can call methods on it for as long as you hold a reference to it.