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.
The close() method of Java DatagramSocket class closes this datagram socket. If any channel is associated with this socket, it will also get closed.
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.
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming using the UDP instead of TCP.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With