Reputation: 3391
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();
}
}
}
Upvotes: 0
Views: 2483
Reputation: 13535
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.
Upvotes: 2