zoukankan      html  css  js  c++  java
  • when an event of selector will be fired

    OP_READ

    Operation-set bit for read operations.

    Suppose that a selection key's interest set contains OP_READ at the start of a selection operation. If the selector detects that the corresponding channel is ready for reading, has reached end-of-stream, has been remotely shut down for further reading, or has an error pending, then it will add OP_READ to the key's ready-operation set and add the key to its selected-key set. 

    OP_WRITE

    写就绪相对有一点特殊,一般来说,你不应该注册写事件。写操作的就绪条件为底层缓冲区有空闲空间,而写缓冲区绝大部分时间都是有空闲空间的,所以当你注册写事件后,写操作一直是就绪的,选择处理线程全占用整个CPU资源。所以,只有当你确实有数据要写时再注册写操作,并在写完以后马上取消注册。

    当有数据在写时,将数据写到缓冲区中,并注册写事件。

    public void write(byte[] data) throws IOException {
        writeBuffer.put(data);
        key.interestOps(SelectionKey.OP_WRITE);
    }
    

      注册写事件后,写操作就绪,这时将之前写入缓冲区的数据写入通道,并取消注册。

    channel.write(writeBuffer);
    key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    

    set OP_WRITE Only when you have data ready

    A common mistake is to enable OP_WRITE on a selection key and leave it set. This results in the selecting thread spinning because 99% of the time a socket channel is ready for writing. In fact the only times it's not going to be ready for writing is during connection establishment or if the local OS socket buffer is full. The correct way to do this is to enable OP_WRITE only when you have data ready to be written on that socket channel. And don't forget to do it from within the selecting thread.

     只有数据可以写时才注册OP_WRITE操作。  


    避免死锁的一个简单方法就是不要在同一个socket同时注册多个操作。

  • 相关阅读:
    为什么包含多句代码的宏要用do while包括起来?
    Android之JUnit深入浅出
    android unit test
    dlopen,dlsym的问题,实在搞不明白了。
    pthread多线程学习笔记五条件变量2使用
    posix多线程程序使用条件变量的一个常见bug
    Android Bitmap和Canvas学习笔记
    c++filt
    pthread_cond_signal只能唤醒已经处于pthread_cond_wait的线程
    百度知道推广技巧大全
  • 原文地址:https://www.cnblogs.com/silentjesse/p/3532122.html
Copyright © 2011-2022 走看看