zengr
zengr

Reputation: 38919

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)

Upvotes: 2

Views: 4597

Answers (2)

Stephen C
Stephen C

Reputation: 719739

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.

Upvotes: 3

user207421
user207421

Reputation: 311052

You can't use select() on a blocking channel, as the Javadocs say. You more or less have to use the model of a thread per channel.

What is the reason for this strange requirement?

Upvotes: 1

Related Questions