Search code examples
javaasynchronousniochannel

Java NIO - non-blocking channels vs AsynchronousChannels


Java NIO offers SocketChannel and ServerSocketChannel which can be set to non-blocking mode (asynchronous). Most of the operations return a value that corresponds to success or that the operation is not yet done. What is the purpose of AynchronousSocketChannel and AsynchronousServerSocketChannel then, apart from the callback functionalities?


Solution

  • which can be set to non-blocking mode (asynchronous)

    There's your misapprehension, right there. Non-blocking mode is different from asynchronous mode.

    A non-blocking operation either transfers data or it doesn't. In either case there is no blocking, and the operation is complete once it returns. This mode is supported by SocketChannel, DatagramSocketChannel, and Selector.

    An asynchronous operation starts when you call the method and continues in the background, with the result becoming available at a later time via a callback or a Future. This mode is supported by the AsynchronousSocketChannel etc classes you mention in your question.