Java AsynchronousSocketChannel

Java AsynchronousSocketChannel

Using Future


Example:
AsynchronousSocketChannel ch = ...
ByteBuffer buf = ...
Future<Integer> result = ch.read(buf);

Example:
AsynchronousSocketChannel ch = ...
ByteBuffer buf = ...
Future<Integer> result = ch.read(buf);
// check if I/O operation has completed
boolean isDone = result.isDone();

Example:
AsynchronousSocketChannel ch = ...
ByteBuffer buf = ...
Future<Integer> result = ch.read(buf);
// wait for I/O operation to complete
int nread = result.get();

Example:
AsynchronousSocketChannel ch = ...
ByteBuffer buf = ...
Future<Integer> result = ch.read(buf);
// wait for I/O operation to complete with timeout
int nread = result.get(5, TimeUnit.SECONDS);

CompletionHandler
> V = type of result value
> A = type of object attached to I/O operation
● Used to pass context
● Typically encapsulates connection context
> completed method invoked if success
> failed method invoked if I/O operations fails


Using CompletionHandler
class Connection { … }
class Handler implements CompletionHandler<Integer,Connection> {
 public void completed(Integer result, Connection conn) {
 int nread = result;
 // handle result
 }
 public void failed(Throwable exc, Connection conn) {
 // error handling
 }
}

Using CompletionHandler
class Connection { … }
class Handler implements CompletionHandler<Integer,Connection> {
 public void completed(Integer result, Connection conn) {
 // handle result
 }
 public void failed(Throwable exc, Connection conn) {
 // error handling
 }
}
AsynchronousSocketChannel ch = ...
ByteBuffer buf = ...
Connection conn = ...
Handler handler = ...
ch.read(buf, conn, handler);


AsynchronousSocketChannel.read()
Once a connection has been accepted, it is now time to
read some bytes:
AsynchronousSocketChannel.read(ByteBuffer b,
 Attachement a,
CompletionHandler<> c);
> Hey Hey  You see the problem, right?
> Who remember when I was scared by the
SelectionKey.attach()?

Trouble trouble trouble:
– Let’s say you get 10 000 accepted connections
– Hence 10 000 ByteBuffer created, and the read
operations get invoked
– Now we are waiting, waiting, waiting, waiting for
the remote client(s) to send us bytes (slow clients/
network)
– Another 10 000 requests comes in, and we are
again creating 10 000 ByteBuffer and invoke the
read() operations.
> BOOM!

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations