首页 > 解决方案 > 非阻塞读取大约需要 100 毫秒

问题描述

我正在使用 JAVA NIO,SocketChannel如下所示:

   while (true) {
        int readyOperations = selector.select();
        if (readyOperations == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();

            if (key.isReadable()) {
                handleRead(key);
            }
            [...]

然后,在里面handleRead我有这段代码:

public void handleRead(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    ByteBuffer buf = (ByteBuffer) key.attachment();

    long nanoStart = System.nanoTime();
    System.out.println("is channel blocking?: " + channel.isBlocking());
    int bytesRead = channel.read(buf);
    long nanoEnd = System.nanoTime();
    System.out.println("elapsed time (ms): " + (nanoEnd - nanoStart) / 1000_000.0);

虽然我使用的是非阻塞通道,但第一次handleRead被称为我得到了很大的经过时间。例如:

is channel blocking?: false
elapsed time (ms): 123

第一次handleRead通话后,我得到了较小的值(< 0.5ms),elapsed time (ms)这似乎是合理的。但是,偶尔我可以看到大约 10 毫秒的时间。

这似乎没有意义,因为我使用的通道是非阻塞的。为什么读取数据需要超过 1ms 的时间?经过的时间是否与在某个时间点读取的数据量有关?但是,即便如此,我预计一次读取约 1000 字节的成本将低于 <1ms。ByteBuffers我使用的是ed allocateDirect

标签: javaniononblocking

解决方案


推荐阅读