Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop this kind of thread?

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.

like image 481
Sarjit Delivala Avatar asked Dec 10 '25 09:12

Sarjit Delivala


2 Answers

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.

like image 169
Philipp Avatar answered Dec 11 '25 22:12

Philipp


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.

like image 20
Lt. Pigeon Avatar answered Dec 11 '25 23:12

Lt. Pigeon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!