0

I've been tearing into the Netty networking library trying to learn how to write some basic NIO networking code when I ran into something that didn't look right to me, a for-loop without anything inside of it, here's the code:

for (;;) {
    SocketChannel acceptedSocket = channel.socket.accept();
    if (acceptedSocket == null) {
        break;
    }
    registerAcceptedChannel(channel, acceptedSocket, thread);
}

I immediately checked the documentation tutorials of loops, located here and couldn't find anything relating to this statement.

The commentation directly above this code states the following:

 // accept connections in a for loop until no new connection is ready

But this doesn't really explain to me how it works, or why, it just says what it's doing.

If you need the entire method, here it is:

 @Override
protected void process(Selector selector) {
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    if (selectedKeys.isEmpty()) {
        return;
    }
    for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) {
        SelectionKey k = i.next();
        i.remove();
        NioServerSocketChannel channel = (NioServerSocketChannel) k.attachment();

        try {
            // accept connections in a for loop until no new connection is ready
            for (;;) {
                SocketChannel acceptedSocket = channel.socket.accept();
                if (acceptedSocket == null) {
                    break;
                }
                registerAcceptedChannel(channel, acceptedSocket, thread);
            }
        } catch (CancelledKeyException e) {
            // Raised by accept() when the server socket was closed.
            k.cancel();
            channel.close();
        } catch (SocketTimeoutException e) {
            // Thrown every second to get ClosedChannelException
            // raised.
        } catch (ClosedChannelException e) {
            // Closed as requested.
        } catch (Throwable t) {
            if (logger.isWarnEnabled()) {
                logger.warn(
                        "Failed to accept a connection.", t);
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                // Ignore
            }
        }
    }
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Hobbyist
  • 15,888
  • 9
  • 46
  • 98

1 Answers1

5

for (;;) is an infinite loop, which is equivalent to while (true). Because the for-loop has no termination statement, it will never terminate.

All three components in a for-loop are optional: for (initialization; termination; increment)

August
  • 12,410
  • 3
  • 35
  • 51