12
votes

NIO and TCP make a great pair for many connections. Since a new connection needs to be opened for each new client, each of these clients would typically need their own thread for blocking I/O operations. NIO addresses that problem by allowing data to be read when it can, rather than blocking until it is available. But what about UDP?

I mean, connectionless UDP does not have the blocking nature of TCP associated with it because of how the protocol is designed (send it and forget it, basically). If I decide to send some data to some address, then it will do so, without delays (on server-end). Likewise, if I want to read data, I can just receive individual packets from different sources. I don't need to have many connections to many places using many threads to deal with each of them.

So, how does NIO and selectors enhance UDP? More specifically, when would one prefer to use UDP with NIO rather than the ol' java.net package?

2
Not an answer to your question - but you should first check if NIO is faster or better even for TCP - mailinator.blogspot.in/2008/02/… paultyma.blogspot.in/2008/03/…user93353

2 Answers

9
votes

Well the DatagramSocket.receive(...) method is documented as a blocking operation. So for instance if you had one thread that is trying to handle packets from N different sockets, you would need to use NIO and selectors. Similarly, if the thread had to multiplex checking for new packets with other activities, you might do this.

If you don't have these or similar requirements, then selectors won't help. But that's no different to the TCP case. You shouldn't use selectors with TCP if you don't need them, because it potentially adds an extra system call.

(On Linux, in the datagram case, you'd do a select syscall followed by a recv ... instead of just a recv.)


But if you're only dealing with one DatagramSocket, wouldn't the receive method read packets immediately as they arrive, regardless of the fact that they're from a different computer?

If you are listening on one socket for datagrams from "everyone" then yes. If you have different sockets for different computers then no.

And for the TCP comment, sometimes the use of a selector is justified simply by the fact that it is very resource demanding to have thousands of threads, as it would be required by a blocking TCP server.

We weren't discussing that case. But yes, that is true. And the same is true if you have thousands of threads blocking on UDP receives.

My point was that it you don't have lots of threads, or if it doesn't matter if a thread blocks, then NIO doesn't help. In fact, it may reduce performance.

4
votes

NIO removes the necessity for threads altogether. It lets you handle all your clients in one thread, including both TCP and UDP clients.

connectionless UDP does not have the blocking nature of TCP associated with it

That's not true. Receives still block, and so can sends, at least in theory.