Search code examples
javasocketsioniochannel

Order of non-blocking writes in Java


Java's NIO provides lots of useful features. One of them is the possibility of non blocking write operations on channels. This means that the write method will not block until the write is done.

But is it still provided that all writes are written in the same order as the writes are called even though the methods don't block?


Solution

  • The scenario you're considering is unlikely, considering the fact that the NIO api does not allow a program to write to the same channel, within the same thread, before a previous write completes. A WritePendingException is thrown. From the docs:

    Unchecked exception thrown when an attempt is made to write to an asynchronous socket channel and a previous write has not completed.

    The way the Async API is built, the most you can do is either attempt to write from a different thread, or wait until the first write is complete before initiating another