SocketChannel读取高CPU负载

时间:2016-03-31 13:58:28

标签: java performance sockets cpu socketchannel

我将SocketChannel配置为只读SelectionKey.OP_CONNECT | SelectionKey.OP_READ Profiler显示runChannel是最耗费CPU的方法,实际上它是合理的,因为它的无限循环始终调用方法selector.select(),但另一方面我有几十个这样的连接和它会杀死CPU 是否有可能减少CPU负载,同时不会错过任何传入消息?

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());
    }

}

1 个答案:

答案 0 :(得分:1)

取消订阅OP_CONNECT - 如果您已订阅OP_CONNECT并已连接,则select()不会阻止。