title: Registration policies for read and write when working with NIO sockets
body: <p>When working with NIO sockets in Java, once I'm connected I can either register for both read and write operations and just do nothing whenever I get a write notification and I have nothing in the outbound buffer, or I can register for read notifications only and re-register for read and write only when something is placed in the outbound buffer.  I'm leaning towards the latter but I'm concerned about two things.  </p>
  
  <ul>
  <li>Would frequent reregistration of interested operations impose any significant performance penalty?  </li>
  <li>Would the reregistration of interested operations in another thread than the one doing the IO operations pose any problem?</li>
  </ul>
  
  <p>EDIT:</p>
  
  <p>Actually another one occured to me.  In order to work properly I need to turn on the write registration in the thread that's adding outbound data to the socket, and in the communication thread I need to turn off write registration when the outbound queue is empty.    However, this leaves open the following scenario</p>
  
  <pre><code>      IO Thread                                    Other Thread
    Check if buffer empty
                                                 Add Item to buffer
                                             Register for write notification 
  Turn off write notifications 
  </code></pre>
  
  <p>The only way I see to avoid this is to turn on thread synchronization on the buffer itself so that modifications to (or checking) the buffer and changing of registration based on that becomes an atomic operation.</p>