JAVA NIO中selectedKeys返回的鍵集,對其中的SelectionKey執行操作之後,是否需要在selectedKeys()中對其執行remove 操作

來源:互聯網
上載者:User

標籤:

今天一個東西需要用到java nio的東西。在網上查了一下資料,發現有Apache的Mina,Netty等,感覺JDK中帶的NIO有點雞肋啊。之前看過這部分的內容,但好長一段時間沒有用,也就忘得七七八八了。如今是溫故而知新,但其中遇到了些疑問:

先貼上代碼吧:

public static void main(String[] args) throws Exception{Thread sh=new Thread(new Runnable() {public void run(){try{ServerSocket ss=new ServerSocket(3000);Socket client=ss.accept();OutputStream os=client.getOutputStream();while(true){os.write("Helloworld".getBytes());Thread.sleep(1000);}}catch(Exception e){e.printStackTrace();}}});sh.start();SocketChannel sc=SocketChannel.open();sc.socket().connect(new InetSocketAddress("localhost",3000) );sc.configureBlocking(false);Selector selector=Selector.open();sc.register(selector,SelectionKey.OP_READ);ByteBuffer byteBuffer=ByteBuffer.allocate(1000);while(true){if(selector.select()>0){Set<SelectionKey> sks=selector.selectedKeys();for(SelectionKey key:sks){if(key.isReadable()){System.out.println("is Readable() ");SocketChannel isc=(SocketChannel)key.channel();isc.read(byteBuffer);}sks.remove(key);}}System.out.println("return from select() ");}}

  

關於是否需要sks.remove(key)這一行呢。

按照上面啟動並執行結果:

is Readable() return from select() is Readable() return from select() is Readable() return from select() is Readable() return from select()

然後把sks.remove(key)這一行注釋掉,再次運行:

is Readable()return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() ...

說明了,如果不對已經處理完的SelectionKey在selectedKyes中執行remove操作的話。下一次select()操作將會直接返回,但其返回的值是0

 

JAVA NIO中selectedKeys返回的鍵集,對其中的SelectionKey執行操作之後,是否需要在selectedKeys()中對其執行remove 操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.