SocketChannel connect blocks in non-blocking mode
Didac Vega Bru
dvb.soln at gmail.com
Mon Sep 18 20:36:16 UTC 2023
Hello,
I typically use SocketChannel using blocking mode but lately I was
trying to use non-blocking operations. The issue I find is that,
according to the javadoc for the connect method of SocketChannel, I
would expect the method to return immediately either with a true, false
or fail fast.
SO, trying a piece of code like the following:
var socket = SocketChannel.open();
socket.configureBlocking(false);
socket.connect(new InetSocketAddress("non.existing.address", 1111));
It turns out that the method does not return immediately but blocks
until it throws (the expected) UnresolvedAddressException. This can take
some time, specially if DNS is badly configured.
| Exception java.nio.channels.UnresolvedAddressException
| at Net.checkAddress (Net.java:149)
| at Net.checkAddress (Net.java:157)
| at SocketChannelImpl.checkRemote (SocketChannelImpl.java:816)
| at SocketChannelImpl.connect (SocketChannelImpl.java:839)
| at (#4:1)
Looking at the code for the connect method in SocketChannelImpl, one can
find that the first statement of the method is
@Override
public boolean connect(SocketAddress remote) throws IOException {
SocketAddress sa = checkRemote(remote);
try {
...
So, effectively, the address name resolution is performed always blocking.
Now the question is, I would expect that in non-blocking mode always
return immediately, and catch all non-immediate possible exceptions
later with a call to finishConnect (which name resolution would be part
of). Therefore is this like this for some technical reason? And in that
case shouldn't the javadoc explicitly point this out?
Thank you,
Didac V.
More information about the nio-dev
mailing list