title: java asynchronous socket channel/completion handler
body: <p>According to this post: <a href="https://stackoverflow.com/questions/6666659/threading-implications-of-asynchronousbytechannel"> https://stackoverflow.com/questions/6666659/threading-implications-of-asynchronousbytechannel</a> the java implementation of asynchronous socket channel doesn't guarantee that completion handler gets called in a separate thread. So if you are reading into a byte buffer, how do you get notify() called after wait()?</p>
  
  <pre><code>        class CH implements CompletionHandler&lt;Integer,Integer&gt;
         {            
              public volatile int i = 0;
              public void completed(Integer i, Integer o)
              {
                 this.i = i;
                 synchronized(this)
                  {
                      this.notify();
               }
             }
  
          public void failed(Throwable t, Integer o)
          {
              this.i = -5;                
              synchronized(this)
              {
                  this.notify();
              }
          }
  
      }
  
                 CH x = new CH();
                synchronized (x) {            
                      while (!(x.i == -1 || x.i == -5)) {
                              aschannel.read(bytebuffer, 5, TimeUnit.SECONDS, null, x);
                               x.wait();                                           
                               if(x.i != -1 &amp;&amp; x.i != -5){
                                    bytebuffer.flip();
                                     filechannel.write(bytebuffer.array,0,x.i);
                                     bytebuffer.clear();
                                 }
                 }     
  
  
                }
  </code></pre>