Pawel Veselov
Pawel Veselov

Reputation: 4225

Does order of operation and registration matter on selectable channel?

I couldn't clearly understand this from java documentation.

Consider I have a selectable channel (SocketChannel), in non-blocking mode.

If I call channel.connect(), and it returns false, and I then register the channel with a selector, would select() ever update the created key with "connect" operation, if the connection was actually finished before the select() was first invoked, or even before the registration was done?

The order of events would be:

This applies to other operations as well. In general, does it matter when the channel is registered in relation to the last operation done on that channel, or would selection key receive all the outstanding events that happened since last channel operation anyway?

Upvotes: 1

Views: 144

Answers (1)

Lolo
Lolo

Reputation: 4357

According to the Javadoc for SocketChannel:

Socket channels support non-blocking connection: A socket channel may be created and the process of establishing the link to the remote socket may be initiated via the connect method for later completion by the finishConnect method. Whether or not a connection operation is in progress may be determined by invoking the isConnectionPending method.

Additionally, the doc for SocketChannel.connect() states:

If the connection is established immediately, as can happen with a local connection, then this method returns true. Otherwise this method returns false and the connection operation must later be completed by invoking the finishConnect method

So the sequence of events should be:

  • channel.connect() - returns false
  • channel.register()
  • selector.select()
  • when the channel is selected, call channel.finishConnect()
  • if finishConnect() returns true, deregister the channel for OP_CONNECT

So yes, the selector will make sure that the selection for this socket channel is placed in its ready set for OP_CONNECT

Upvotes: 0

Related Questions