Interrupt a thread in DatagramSocket.receive Interrupt a thread in DatagramSocket.receive multithreading multithreading

Interrupt a thread in DatagramSocket.receive


A common idiom for interrupting network IO is to close the channel. That would be a good bet if you need to effectively interrupt it while its waiting on sending or receiving.

public class InterruptableUDPThread extends Thread{   private final DatagramSocket socket;   public InterruptableUDPThread(DatagramSocket socket){      this.socket = socket;   }   @Override   public void interrupt(){     super.interrupt();       this.socket.close();   }}


As far as I know, close() is the proper way to interrupt a blocked socket. Interrupting and keeping open something that may have already done a partial read or write makes things unnecessarily complex. It's easier to only have to deal with a "success" or "give up" result.


DatagramSocket.receive blocks until it receives a datagram. Probably what you need to do is use setSoTimeout to make it timeout.