I have a thread running in my Swing chat application to listen indefinitely through a socket for datagrams. When I close this application, I have the following code execute:
listenThread.interrupt();
socket.close();
However, interrupt doesn’t seem to be stopping the thread, as when the socket closes, the loop continues listening, and throws exceptions since the socket has been closed. How do I get the thread to exit properly so that I can close the socket safely?
interrupt()cannot be used to interrupt an I/O operation such as socket reads or writes. To abort the I/O, closing the socket is the right way. After your thread receives theIOExceptionit should check if it was interrupted in the meantime and then gracefully exit.Example for the code in your I/O thread: