Search code examples
javanio

Configurable blocking and non-blocking requests in NIO


I am planning to use java NIO for my project, but one of my requirement is to keep the requests configurable, i.e. the client can select the request to be: 1. blocking, 2. non blocking.

So, is it possible to use NIO in a sync. way?

There is an option on the client code when creating the channel:

SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);

But, I get this error when I make it as true.

This is the client code I am using from this tutorial.

java.nio.channels.IllegalBlockingModeException
    at java.nio.channels.spi.AbstractSelectableChannel.register(AbstractSelectableChannel.java:172)
    at java.nio.channels.SelectableChannel.register(SelectableChannel.java:254)
    at com.dds.client.DDSClient.run(DDSClient.java:77)
    at java.lang.Thread.run(Thread.java:680)

Solution

  • The javadocs for register(...) state that if you call the method on a channel that is in blocking mode, that exception will be thrown. A selector can only handle a non-blocking channel.

    You need to change your code to use a blocking operations (e.g. read or write) rather than register and select when you want blocking semantics.