SocketChannel 高 CPU 读取时加载
SocketChannel high CPU load on read
我将 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());
}
}
取消订阅 OP_CONNECT - 如果您订阅 OP_CONNECT 并已连接,select() 将不会阻止。
我将 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());
}
}
取消订阅 OP_CONNECT - 如果您订阅 OP_CONNECT 并已连接,select() 将不会阻止。