Java Reference
In-Depth Information
into some backend. Because you don't care about the order of the responses returned,
you can spawn a large number of AsynchronousSocketChannel requests and give each
one a CompletionHandler that stores the results in the backend.
The generic CompletionHandler interface declares two methods: completed() , which
is invoked if the read finishes successfully; and failed() , which is invoked on an I/O
error. For example, here's a simple CompletionHandler that prints whatever it received
on System.out :
class LineHandler implements CompletionHandler<Integer, ByteBuffer> {
@Override
public void completed(Integer result, ByteBuffer buffer) {
buffer.flip();
WritableByteChannel out = Channels.newChannel(System.out);
try {
out.write(buffer);
} catch (IOException ex) {
System.err.println(ex);
}
}
@Override
public void failed(Throwable ex, ByteBuffer attachment) {
System.err.println(ex.getMessage());
}
}
When you read from the channel you pass a buffer, an attachment, and a Completion
Handler to the read() method:
ByteBuffer buffer = ByteBuffer.allocate(74);
CompletionHandler<Integer, ByteBuffer> handler = new LineHandler();
channel.read(buffer, buffer, handler);
Here I've made the attachment the buffer itself. This is one way to push the data read
from the network into the CompletionHandler where it can handle it. Another common
pattern is to make the CompletionHandler an anonymous inner class and the buffer a
final local variable so it's in scope inside the completion handler.
Although you can safely share an AsynchronousSocketChannel or AsynchronousSer
verSocketChannel between multiple threads, no more than one thread can read from
this channel at a time and no more than one thread can write to the channel at a time.
(One thread can read and another thread can write simultaneously, though.) If a thread
attempts to read while another thread has a pending read, the read() method throws
a ReadPendingException . Similarly, if a thread attempts to write while another thread
has a pending write, the write() method throws a WritePendingException .
Search WWH ::




Custom Search