What is the point of using UDP with NIO?

NIO and TCP make a great pair for many connections. Since each new client needs to open a new connection, each of these clients will usually need its own thread to block I / O operations. NIO solves this problem by letting it read data whenever possible, rather than blocking it until it is available. But what about UDP?

I mean, UDP without a connection does not have the TCP blocking nature associated with it, due to the way the protocol is designed (send it and forget it mostly). If I decide to send some data to some address, then he will do it without delay (on the server). Similarly, if I want to read data, I can just get individual packets from different sources. I do not need to have many connections in many places, using many threads to work with each of them.

So how do NIOs and selectors improve UDP? More specifically, when do you prefer to use UDP with NIO rather than with ol ' java.net ?

+8
java udp networking tcp nio
source share
2 answers

Well, the DatagramSocket.receive(...) method is documented as a blocking operation. For example, if you have one thread that is trying to process packets from N different sockets, you will need to use NIO and selectors. Similarly, if the stream was to multiplex the check for new packets with other actions, you can do this.

If you do not have these or similar requirements, this will not help selectors. But this is no different from the case of TCP. You should not use selectors with TCP if you do not need them, because this potentially adds an additional system call.

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


But if you are dealing with only one DatagramSocket, will the receiving method not read packets immediately as they arrive, regardless of whether they are from another computer?

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

And for a TCP comment, sometimes the use of a selector is justified simply by the fact that it is very resource intensive, requiring thousands of threads, as a blocking TCP server would require.

We did not discuss this case. But yes, thatโ€™s true. And the same is true if you have thousands of thread locks on UDP.

My point was that you do not have many threads, or if it doesnโ€™t matter , if the thread is blocked, then NIO does not help. In fact, this can reduce performance.

+8
source share

NIO completely eliminates the need for threads. It allows you to process all your clients in one thread, including both TCP and UDP clients.

without establishing a connection, UDP does not have the blocking nature of the TCP associated with it

This is not true. It still receives a block, and therefore can be sent, at least theoretically.

+3
source share

All Articles