0

According to this post: https://stackoverflow.com/questions/6666659/threading-implications-of-asynchronousbytechannel 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()?

        class CH implements CompletionHandler<Integer,Integer>
       {            
            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 && x.i != -5){
                                  bytebuffer.flip();
                                   filechannel.write(bytebuffer.array,0,x.i);
                                   bytebuffer.clear();
                               }
               }     


              }
Community
  • 1
  • 1
Sam Adamsh
  • 3,331
  • 8
  • 32
  • 53

1 Answers1

2

Your program may work, because wait() releases the monitor and allow callbacks to execute.

However, the whole idea of asynchronous I/O is to free the I/O exchange initiator from waiting (and so holding the thread). If you want to wait anyway, then simply use good old synchronous API. Or call read without CompletionHandler, which returns Future, and wait on that Future.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
  • synchronous i/o is very buggy, and stalls when connecting with slow servers, even with read timeouts. Asynchronous future methods don't throw the interrupted by timeout exceptions, and sometimes stall on read operations. Only the Completion handler methods will interrupt. – Sam Adamsh Nov 13 '12 at 19:00
  • 1
    If you really want to use `CompletionHandler`s, look at my library df4j-nio2 (part of https://github.com/rfqu/df4j). It uses Nio2 in Actor style. – Alexei Kaigorodov Nov 14 '12 at 03:11