【问题标题】:Selector.select do not block as expectedSelector.select 不会按预期阻塞
【发布时间】:2011-11-07 03:27:35
【问题描述】:

在我当前的项目中,我注意到select() 没有按预期阻止。 它根本不会阻塞并总是返回,即使没有 IO 存在。所以我的 CPU 很忙。

注册总是会被另一个线程调用,所以我需要锁和唤醒。

文档说selectNow()

调用此方法会清除任何先前调用唤醒方法的效果。

所以我在每次迭代结束时调用该方法。没有成功。 我没有找到任何示例或说明如何将selectNow 用于我的目的。

代码有什么问题?


这是我的示例代码,你可以测试一下。

顺便说一句:另一个 stackoverflow 问题是我的代码的角色模型。 编辑:示例已修复!现在可以了。

import java.io.IOException;
import java.net.*;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.locks.ReentrantLock;

public class Test implements Runnable {
    ReentrantLock selectorLock = new ReentrantLock();
    Selector selector;
    boolean alive;

    @Override
    public void run() {
        SelectionKey key;
        Iterator<SelectionKey> keys;

        alive = true;
        try {
            while (alive) {
                selectorLock.lock();
                selectorLock.unlock();

                selector.select();
                System.out.println("select() returned");

                keys = selector.selectedKeys().iterator();
                // handle each "event"
                while (keys.hasNext()) {
                    key = keys.next();
                    // mark as handled
                    keys.remove();
                    // handle
                    handleKey(key);
                }
                //selector.selectNow(); // don't fix this
            }
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    private void handleKey(SelectionKey key)
        throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            System.out.println("connecting");
            if ( channel.finishConnect() ) {
                key.interestOps(SelectionKey.OP_READ);
            } else {
                key.cancel();
            }
        } else if (key.isReadable()) {
            System.out.println("reading");
            // read and detect remote close
            channel.read(ByteBuffer.allocate(64));
        }
    }

    public void register(SelectableChannel channel, int ops, Object attachment)
        throws ClosedChannelException {
        selectorLock.lock();
        try {
            System.out.println("wakeup");
            selector.wakeup();
            channel.register(selector, ops, attachment);
        } finally {
            selectorLock.unlock();
        }
    }

    public Test()
        throws IOException {
        selector = Selector.open();
    }

    public static void main(String[] args)
        throws IOException {
        Test t = new Test();
        new Thread(t).start();

        SocketAddress address = new InetSocketAddress("localhost", 8080);
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(address);

        t.register(channel, SelectionKey.OP_CONNECT, "test channel attachment");
    }
}

【问题讨论】:

    标签: java multithreading locking nio


    【解决方案1】:

    OP_CONNECT 触发并且 finishConnect() 返回“true”之前,不要注册OP_READ。此时您必须注销OP_CONNECT

    同样,在你有东西要写之前不要为 OP_WRITE 注册通道。 OP_WRITE 始终准备就绪,除非套接字发送缓冲区已满,因此它应该只在您检测到该条件之后进行注册(write() 返回零),并且您应该立即取消注册它它会触发(除非这种情况再次发生)。

    最后OP_CONNECTOP_WRITE 在底层是一样的,鉴于我刚才所说的OP_WRITE 解释了你的选择器旋转。

    【讨论】:

    • 谢谢。你的提示解决了这个问题。我换了handleKey
    • 您可以通过在所需的 selectionKey 上调用 interestOps 方法来取消注册特定的 OP_*,并将其设置为您现在想要收到通知的内容。比如:selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    猜你喜欢
    • 2015-07-19
    • 1970-01-01
    • 2010-12-23
    • 2014-09-10
    • 2015-08-06
    • 2014-05-25
    • 1970-01-01
    • 2014-12-15
    • 2014-05-24
    相关资源
    最近更新 更多