title: Why the key should be removed in `selector.selectedKeys().iterator()` in java nio?
body: <p>I found some sample code of java nio:</p>
  
  <pre><code> ServerSocketChannel server = ServerSocketChannel.open();  
   Selector selector = Selector.open();  
   server.socket().bind(new InetSocketAddress(8080));  
   server.configureBlocking(false); 
   server.register(selector, SelectionKey.OP_ACCEPT);  
  
   while(true) {
       selector.select(); 
       Iterator iter = selector.selectedKeys().iterator();  
       while (iter.hasNext()) {  
           SelectionKey key = (SelectionKey) iter.next();  
           iter.remove();  // Why remove it? 
           process(key);  
       }
   }
  </code></pre>
  
  <p>When he gets the selected keys, he remove the key in the loop. Why we should do this?</p>
  
  <hr>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Thanks to the answers provided by <strong>EJP</strong> and <strong>user270349</strong>, I think I understand it now, let me explain it in detail.</p>
  
  <p>There are 2 tables in the selector:</p>
  
  <ol>
  <li><p>registration table: when we call <code>channel.register</code>, there will be a new item(key) into it. Only if we call <code>key.cancel()</code>, it will be removed from this table.</p></li>
  <li><p>ready for selection table: when we call <code>selector.select()</code>, the selector will look up the registration table, find the keys which are available, copy the references of them to this selection table. The items of this table won't be cleared by selector(that means, even if we call <code>selector.select()</code> again, it won't clear the existing items)</p></li>
  </ol>
  
  <p>That's why we have to invoke <code>iter.remove()</code> when we got the key from selection table. If not, we will get the key again and again by <code>selector.selectedKeys()</code> even if it's not ready to use.</p>