Search code examples
javaasynchronouscallbacknetwork-programmingnio

How do callbacks behave in the NIO.2 library


I'm building a small client/Server chat application. I came across NIO.2 after I tried to simulate it using the classic NIO library.

The goal of my "simulation" of the NIO.2 lib with the classisc NIO, was to use multiple selectors in multiple threads which are in pairs connected through a ArrayBlockingQueue, to avoid the network read and write times.

My question is, how are multiple events at the same time handled with in the NIO.2 lib using AsynchronousSocketChannels and CompletionHandlers (which act to my understanding as callbacks)?

The classic NIO lib uses Selectors which deliver after a select call a key set. This key set can then be iterated over and each event(read,accept and write) can be handled one after another.

The NIO.2 callbacks on the other hand, don't have such a sequence. They are asyncronous. So what happens if, for example, 2 clients send at exact the same moment a message to the server ?

Do then 2 callbacks run at the same time? And if yes, then how? Do they each run in seperate threads or not?

And if I were to take those messages from each of the callbacks and tried to enqueue them in a as before mentioned ArrayBlockingQueue, would they wait for each other or not ?


Solution

  • So what happens if, for example, 2 clients send at exact the same moment a message to the server ?

    The clients do not share a common connection with the server. Server-sided, you'd call AsynchronousSocketChannel#read with your callback for both clients, which would fire when some bytes arrive.

    For that reason, two callbacks can run simultaneously (as they're asynchronous), but they're still independent for each client, so there won't be a problem.

    Do they each run in seperate threads or not?

    This depends on the backing AsynchronousChannelGroup's thread pool (which you can specify yourself or use the default group).

    I created a simple networking library with NIO.2, which I think would help you: https://github.com/jhg023/SimpleNet