I have one thread that has this code
while(!this.isInterrupted()) {
try {
socket = server.accept();
}
catch(IOException e) {
continue;
}
}
When I call interrupt method from somewhere then it will stop executing only if it is checking condition. What if the program is at server.accept() statement? It will not stop till any request comes from any socket. I want that when I call interrupt method this should stop immediately. Is there any solution for this problem.
Override the interrupt() method in your Thread like this:
@Override
public void interrupt() {
super.interrupt();
socket.close();
}
When another thread interrupts this thread, the socket will get closed. When the thread is currently inside accept(), accept will exit immediately by throwing a SocketException. Your catch-block will catch that exception (SocketException is a subclass of IOException) and the check in the while-statement will be performed, which will then notice that the isInterrupted() flag is set and exit.
In contrary to the currently accepted solution it will exit immediately and not wait for up to 10 seconds to do so.
You could set a timeout on your ServerSocket:
server.setSoTimeout(10000);
When you call the accept method now, it will accept new connections for 10 seconds, after that it throws a SocketTimeoutException. Then you can do your accept again.
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