This question has undoubtedly 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 for a network message to be received over UDP.
For example, let's say I have the following topic:
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) {
Now, would it be more appropriate to use the interrupt() method? For example, adding the following method:
@Override public void interrupt() { super.interrupt();
My only problem is that socket.receive() not a lock interrupt method? The only way I thought was to implement the interrupt method, as mentioned above, in this method, call socket.close() , and then serve it in the run method in catch for a SocketException . Or maybe instead of while(true) use some kind of state that falls into the interrupt method. Is this the best way? Or is there a more elegant way?
thanks
source share