9

I'm in the process of writing a piece of code that connects to a server spawns a bunch of threads using that connection and does a bunch of "stuff".

There are certain instances where the connection fails and I need to stop everything and start from scratch with a new object.

I wanted to clean up after the object but calling thread.stop on the threads, but this method is seemingly deprecated.

What is the recommended alternative to doing this? Should I write my own cleanup and exit method for each of the threads? Set the thread to null? or something else?

Omar Kooheji
  • 52,899
  • 67
  • 179
  • 237

3 Answers3

4

Assuming your threads are reasonably under your control - i.e. they're not calling anything which is going to potentially wait forever without your code executing - I would shut it down with a simple (but thread-safe - use volatile!) flag.

See this article for an example in C# - the Java equivalent should be easy to work out. Calling interrupt won't have any effect until the thread next waits, and stop can leave your app in a hard-to-predict state. Wherever possible, go for a clean, orderly shutdown instead.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
1
private Thread m_CleanupThread = null; 

public void threadCleanUp(){
    m_CleanupThread = new Thread(this);
    m_CleanupThread.Start();
}

This thread will terminate and garbage collector will do the rest.

Alex K
  • 21,796
  • 18
  • 106
  • 231
Arun Edwin
  • 11
  • 1
1

Use your_thread.interrupt and check in your thread if Thread.interrupted() return true. If so, close your thread properly.

gizmo
  • 11,733
  • 6
  • 43
  • 60