Chris Chris - 5 months ago 20
Java Question

Create several outgoing connections simultaneously in Java NIO

I'm using Java NIO for a peer to peer protocol and need to create many simultaneous connections of which many will fail. Unfortunately, it seems as if I need to wait for a connection to be established before creating the next one, otherwise I'll get a "BindException: Cannot assign requested address: connect". Does anyone have an idea how to fix this?

for (NetworkAddress address : addresses) {
if (isConnectedTo(address)) {
try {
SocketChannel channel =;
channel.connect(new InetSocketAddress(address.toInetAddress(), address.getPort()));
// admittedly, 20 seconds is quite long
long timeout = System.currentTimeMillis() + 20_000;
while (!channel.finishConnect() && System.currentTimeMillis() < timeout) {
// Without this loop, I get said exception
if (!channel.finishConnect()) {
ConnectionInfo connection = new ConnectionInfo(ctx, CLIENT,
requestedObjects, 0
channel.register(selector, OP_READ | OP_WRITE, connection)
} catch (NoRouteToHostException | AsynchronousCloseException ignore) {
} catch (IOException e) {
LOG.error(e.getMessage(), e);


You can't use the connection before it has finished connecting but you can have any number of pending connections

You can either

  • poll you connecting connection to see if they have connected yet, or
  • add the connection to a Selector by registering an OP_CONNECT.

In either case I suggest calling finishConnect() to ensure it is ready for use.