Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I kill a thread that is waiting for TCP connection to come in?

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?

like image 928
alexgolec Avatar asked Feb 25 '23 13:02

alexgolec


2 Answers

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.

like image 59
Mark Peters Avatar answered Feb 27 '23 01:02

Mark Peters


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.

like image 42
Amir Afghani Avatar answered Feb 27 '23 01:02

Amir Afghani