I would like to kill programatically a thread which is running in a while(true) loop and listening for connections infinetely and since listening is a blocking method I cant simply set the loops statemenet into false. My application is generally swapping networks periodically when connected launches a server to listen for connections, so when it does swap to another network I am afraid that the old server will become a zombie and just stuck there since on the new network the server is bound on different IP than the one it had previously.
PS. will binding the server to localhost not require its reset after network change?
If you need to be able to stop a thread sitting in an
acceptloop, you can just callsetSoTimeoutso that theacceptcall can complete without waiting for an actual connection to happen.Note that if you bind to all interfaces, you probably don’t need to create a new socket when a new network interface is added to the system.
Other possibilities are calling
closeon the socket, orstoporinterrupton the thread. If you can use async I/O, see http://www.developer.com/java/article.php/3837316/Non-Blocking-IO-Made-Possible-in-Java.htm.