Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to stop a thread waiting for network activity?

This question has no doubt been asked in various forms in the past, but not so much for a specific scenario.

What is the most correct way to stop a Thread that is blocking while waiting to receive a network message over UDP.

For example, say I have the following Thread:

public class ClientDiscoveryEngine extends Thread {

    private final int PORT;

    public ClientDiscoveryEngine(final int portNumber) {
        PORT = portNumber;
    }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket(RECEIVE_PORT);

            while (true) {
                final byte[] data = new byte[256];
                final DatagramPacket packet = new DatagramPacket(data, data.length);

                socket.receive(packet);
            }
        } catch (SocketException e) {
            // do stuff 1
        } catch (IOException e) {
            // do stuff 2
        }
    }
}

Now, would the more correct way be using the interrupt() method? For example adding the following method:

@Override
public void interrupt() {
    super.interrupt();
    // flip some state?
}

My only concern is, is socket.receive() not a non-interruptable blocking method? The one way that I have thought of would be to implement the interrupt method as above, in that method call socket.close() and then cater for it in the run method in the catch for the SocketException. Or maybe instead of while(true) use some state that gets flipped in the interrupt method. Is this the best way? Or is there a more elegant way?

Thanks

like image 884
Nico Huysamen Avatar asked Jan 19 '23 22:01

Nico Huysamen


2 Answers

The receive method doesn't seem to be interruptible. You could close the socket: the javadoc says:

Any thread currently blocked in receive(java.net.DatagramPacket) upon this socket will throw a SocketException

You could also use setSoTimeout to make the receive method block only for a small amount of time. After the method has returned, your thread can check if it has been interrupted, and retry to receive again for this small amount of time.

like image 139
JB Nizet Avatar answered Jan 29 '23 12:01

JB Nizet


Read this answer Interrupting a thread that waits on a blocking action?

like image 34
aalku Avatar answered Jan 29 '23 12:01

aalku