SocketChannel connect blocks in non-blocking mode

Alan Bateman Alan.Bateman at oracle.com
Tue Sep 19 07:36:56 UTC 2023



On 18/09/2023 21:36, Didac Vega Bru wrote:
> 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)
>

SocketChannel.connect is specified to throw UAE if the socket address is 
unresolved.  So as others said, creating an InetSocketAddress with a 
host name and port will attempt to resolve the host name, that's where 
you are seeing the delay.

-Alan


More information about the nio-dev mailing list