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