Can I kill a thread waiting for a TCP connection?

I have an application in which a thread listens for TCP connections and needs to be killed. What is the best way to do this? I know that Thread.stop is outdated, interrupts the thread enough?

+4
source share
3 answers

If you have a reference to ServerSocket , you can call the close() method. This will cause the thread waiting on accept() to throw a SocketException .

Note that you probably do not want to show a link to the socket itself; you should probably add a method to your server code called shutdownServer() or similar that does it yourself.

+7
source

Generally, yes, you should use Thread.interrupt () and a shared variable. In your specific example, you can simply close the Socket so that the stream returns immediately. Read about it here .

+1
source

You can set a stop variable that the thread checks after each connection. Then connect to the stream port to wake it up.

Another approach would be to set a timeout with the call to soTimeout() and check the stop variable after each connection and when the timeout occurs. You probably do not want to set the timeout too short. This means that the thread does not stop immediately, so this may not work for you if a quick shutdown is required.

You can also call close () directly on the ServerSocket, if possible, as mentioned by Mark Peters.

0
source

Source: https://habr.com/ru/post/1347476/


All Articles