I have a application where a thread is listening for TCP connections, and will need to be killed. What is the best way to do this? I know that Thread.stop is deprecated, is interrupting the thread enough?
If you have a reference to a ServerSocket
you can call its close()
method. This will cause the Thread waiting on accept()
to throw a SocketException
.
Note that you probably don't want to expose a reference to the socket itself; you should probably add a method to your server code named shutdownServer()
or similar which does this itself.
Generally - yes, you should use Thread.interrupt() and a shared variable. In your particular example, you can just close the Socket to cause the thread to return immediately. Read about it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With