开发者

Java: do I need to protect a Thread object from the Garbage Collector?

After

{
Thread t = new Thread();
t.start();
}
开发者_如何学JAVA

is the Thread object a candidate for the GC?


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.


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...)


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜