Is the ordering nor guarateed?
# coroutines
k
Is the ordering nor guarateed?
j
I see this remark often, and there's something here I don't understand. If I call
.receive()
on a non-blocking NIO channel, it will immediately return with either some available data, or
null
. So if I were to use this in a coroutine, I'd have to do this in an infinite loop, no? Something like:
Copy code
while(true) {
   channel.receive(buffer)
   // handle data if available
}
If I were to implement it like this, wouldn't that make the CPU load 100%? Or am I supposed to implement a delay here to prevent this?
e
You should not use NIO directly. It is very, very, low-level IO API. Use some higher-level async IO library.
Take a look at ktor, for example: https://ktor.io/servers/raw-sockets.html
In general, if you there is some reason to use NIO directly, then you should use selectors and etc. It takes a lot of boilerplate to setup a proper async API on top of that.
TL;DR “nonblocking NIO channel” is not an asynchronous API.
j
Thanks for the reply, which luckily confirms a number of my suspicions 🙂 I just see 'don't use blocking IO' so much that one would think it's obvious how to use non-blocking, while (as you rightfully say) non-bocking and async are two different things. Thanks again!
I looked into Ktor, but from a quick glance I think it can't do multicast UDP sockets at this point, which is what I need. But I'll take a close look.
d
You can ask on #ktor if you don't find anything on it.