• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can you kill a thread  RSS feed

 
Costa lamona
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

if you have a Runnable class and you start it in Timer
Assume that run is in infinite loop
setting all references of that thread to null will kill the thread??

Giving that the class inherits from Thread and run is in infinite loop, setting the class ref to null will
kill the thread immediately or
kill the thread in next garbage collection run or
will not kill the thread because it is actually referenced by Java Virtual Machine somehow.


Thanks
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Threads are referenced by the JVM until they die, so nulling your references has no effect on the running thread (thank goodness).

There is no safe way to kill a thread forcibly. The Thread.stop() method looks like it would do it, but is strongly deprecated, because it can never be relied upon - it can cause "random" hangs etc. Do NOT use it, however tempting that might seem.

You must arrange for your threads to cooperate so they know when to stop. Search this forum and/or Google for many, many discussions on the issue.
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say the thread is called t1.

t1.stop() will kill the thread at once -- that's why the stop() & suspend() methods are deprecated.

A better solution would be to call interrupt() on t1 and have t1 handle the interrupt and gracefully exit.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!