简体   繁体   中英

java.nio DatagramChannel non-blocking mode.. you still have to block?

I've been looking into java.nio's asynchronous capabilities, and so far I am a fan of the AsynchronousByteChannel class, as it lets me provide completion callbacks for each read or write operation. This adapts well with scala's Future class.

Now I'm trying to interact with a DatagramChannel asynchronously. (As a matter of curiosity, I'm trying to implement my own torrent client, and some trackers use UDP.)

My goal right now is to find a means to adapt the current read and write methods from their original signatures...

def write(src: ByteBuffer): Int
def read(dest: ByteBuffer): Int

to a scala-futures-oriented signature like...

def write(src: ByteBuffer): scala.concurrent.Future[Int]
def read(dest: ByteBuffer): scala.concurrent.Future[Int]

Looking into the API and finding examples online, and found my way to the Selector class. As far as I can tell, that's what I need to use to make a DatagramChannel be "non-blocking", but I see three methods that seem relevant:

select() - blocks until a selection is ready
select(timeout) - blocks until either a selection is ready or timeout is reached
selectNow - doesn't block, but is useless if called before a selection is ready

So it appears my choices for "non-blocking" are either to block (wtf?) or to occupy a thread that runs a busy loop that repeatedly calls one of the select methods. This is my problem.

Is there a way to achieve true non-blocking IO using a DatagramChannel ? If not, what is the best way to handle (read 'minimize') the actual blocking?

Exploiting a dedicated selector thread is not a problem at all. First, it is unavoidable. Second, AsynchronousByteChannel implementations also use background threads under the hood.

As for the best way to use Selector, I believe I found one in the SelectorThread implementation (note it is still in the "work" branch). I did not try it with DatagramChannel, but it should work: just implement AsyncDatagramChannel the same way as AsyncSocketChannel1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM