Selector.select不会按预期阻止

Mar*_*hke 4 java multithreading nio locking

在我目前的项目中,我注意到select()没有按预期阻止.即使没有IO,它也不会完全阻塞并始终返回.所以我得到了一个忙碌的CPU.

注册将始终由另一个线程调用,因此我需要锁定和唤醒.

该文件说selectNow():

调用此方法可清除以前调用wakeup方法的效果.

所以我在每次迭代结束时调用该方法.没有succsess.我没有找到任何示例或解释如何selectNow用于我的目的.

代码有什么问题?


这是我的示例代码,因此您可以测试它.

BTW:另一个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");
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*421 9

在OP_CONNECT触发并且 finishConnect()返回'true' 之前,不要注册OP_READ .此时,您必须取消注册OP_CONNECT.

同样,在有东西要写之前,不要为OP_WRITE注册通道.OP_WRITE总是处于准备状态,除非套接字发送缓冲区已满,所以只有在检测到该条件才能注册(write()返回零),并且应该立即取消注册它(除非条件再次发生) .

最后OP_CONNECT和OP_WRITE是同样的事情,我刚才所说的OP_WRITE解释了你的选择器旋转.