Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupt a thread in DatagramSocket.receive

Tags:

I'm building an application that listens on both TCP and UDP, and I've run into some trouble with my shutdown mechanism. When I call Thread.interrupt() on each of the listening threads, the TCP thread is interrupted from listening, whereas the UDP listener isn't. To be specific, the TCP thread uses ServerSocket.accept(), which simply returns (without actually connecting). Whereas the UDP thread uses DatagramSocket.receive(), and doesn't exit that method.

Is this an issue in my JRE, my OS, or should I just switch to (Datagram)Socket.close()?

UPDATE: I've found an analysis of the problem. It confirms that the behavior is not consistent.

like image 317
SEK Avatar asked Jan 12 '11 15:01

SEK


People also ask

How do I close DatagramSocket?

The close() method of Java DatagramSocket class closes this datagram socket. If any channel is associated with this socket, it will also get closed.

Is DatagramSocket UDP or TCP?

DatagramSockets are Java's mechanism for network communication via UDP instead of TCP. Java provides DatagramSocket to communicate over UDP instead of TCP. It is also built on top of IP. DatagramSockets can be used to both send and receive packets over the Internet.

Is DatagramSocket is a UDP endpoint API?

Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming using the UDP instead of TCP.

Which exceptions will occur if a specified port number is not available for DatagramSocket?

Parameters: bindaddr - local socket address to bind, or null for an unbound socket. Throws: SocketException - if the socket could not be opened, or the socket could not bind to the specified local port.


2 Answers

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();    } } 
like image 124
John Vint Avatar answered Nov 11 '22 10:11

John Vint


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.

like image 33
JOTN Avatar answered Nov 11 '22 10:11

JOTN