title: How does Java NIO's selector check for available events under the hood?
body: <p>A similar question has been asked <a href="https://stackoverflow.com/questions/13712847/a-non-blocking-server-with-java-io">before</a>, but I would like to place it again, hoping that someone would help clear out a couple of things. As an experiment, I tried writing a naive "non-blocking" server in Java without using NIO, where essentially three threads are needed:</p>
  
  <ol>
  <li>Main server thread - <code>accept()</code>s new socket connections, and puts each new socket in a queue</li>
  <li>Reading worker thread - goes through each socket in the queue, and reads a little bit out of each socket's input stream, and stores it in an <code>InputQueue</code></li>
  <li>Writing worker thread - depending on when the incoming request gets read out of each socket, this worker would loop over all sockets where a response is needed, and once again, write a few bytes of response on every take. </li>
  </ol>
  
  <p>In the previous question, it was pointed out that Java NIO's <code>select()</code> mechanism is far better than polling on each socket, and sleeping a little after every take through the queue. I know how select works in theory, but the main thing that I struggle to understand is the following: if polling is bad and inefficient, how does <code>select()</code> do it under the hood?</p>
  
  <p><strong>UPDATE:</strong> I found <a href="http://daniel.haxx.se/docs/poll-vs-select.html" rel="nofollow noreferrer">this page</a> which gives a bit more light on how the native <code>select()</code> works under the hood. What is interesting is that indeed, my initial speculations seem to be right: <code>select()</code> works in a linear fashion, probing each of the requested file descriptors, similar to what a polling mechanism would do:</p>
  
  <blockquote>
    <p>They both [<code>select()</code> and <code>poll()</code>] handle file descriptors in a
    linear way. The more descriptors you ask them to check, the slower
    they get. As soon as you go beyond perhaps a hundred file descriptors
    or so - of course depending on your CPU and hardware - you will start
    noticing that the mere waiting for file descriptor activity and the
    following checking which file descriptor that it was, takes a
    significant time and becomes a bottle neck.</p>
  </blockquote>