Search code examples
javaperformancesocketscpusocketchannel

SocketChannel high CPU load on read


I have SocketChannel configured for read only SelectionKey.OP_CONNECT | SelectionKey.OP_READ Profiler shows runChannel is the most CPU consuming method and actually it is reasonable because it's infinite loop which calls method selector.select() all the time, but on the other hand I have dozens of such connections and it kills CPU.
Is there a possibility to decrease CPU load and in the same time do not miss any incoming message?

public void runChannel() {
    while (session.isConnectionAlive()) {
        try {
            // Wait for an event
            int num = selector.select();
            // If you don't have any activity, loop around and wait
            // again.
            if (num == 0) {
                continue;
            }
        } catch (IOException e) {
            log.error("Selector error: {}", e.toString());
            log.debug("Stacktrace: ", e);
            session.closeConnection();
            break;
        }
        handleSelectorkeys(selector.selectedKeys());
    }

}


Solution

  • Unsunscribe from OP_CONNECT - select() won't block if you're subscribed to OP_CONNECT and connected.