Java: do I need to protect a Thread object from th

2019-05-13 00:49发布

问题:

After

{
Thread t = new Thread();
t.start();
}

is the Thread object a candidate for the GC?

回答1:

If it's started, it's not eligible for GC - the code that's running can ask for Thread.currentThread(), after all.

If you just created it but didn't start it, like this:

{
    Thread pointless = new Thread();
}

then I suspect it would be eligible for GC - but it's pretty unusual to create a thread without starting it. (I guess an exception could be thrown before you got round to starting it...)



回答2:

No, its not eligible for Garbage Collection. Since, the thread is scheduled in the runnable queue by the Thread Scheduler( after calling t.start( )), it won't be eligible for GC.

One of the methods to check if the thread is still running or not is to call thread.isAlive().

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise. In your case,you can always call t.isAlive() method, just to check whether the thread is alive or not.

When the thread stops or end's its lifecycle or is not yet scheduled to run (like Jon's Code Snippet), then it's eligible for GC.



回答3:

You only need to protect a Thread if you want to retain it after it has finished. It cannot be GC'ed while it is running (or anything the Thread uses)