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

血红的双手。 提交于 2019-12-22 10:31:34

问题


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)



来源:https://stackoverflow.com/questions/5351836/java-do-i-need-to-protect-a-thread-object-from-the-garbage-collector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!