Java Reference
In-Depth Information
Asynchronous Channels (Java 7)
Java 7 introduces the AsynchronousSocketChannel and AsynchronousServerSock
etChannel classes. These behave like and have almost the same interface as SocketCh
annel and ServerSocketChannel (though they are not subclasses of those classes).
However, unlike SocketChannel and ServerSocketChannel , reads from and writes to
asynchronous channels return immediately, even before the I/O is complete. The data
read or written is further processed by a Future or a CompletionHandler . The con
nect() and accept() methods also execute asynchronously and return Future s. Se‐
lectors are not used.
For example, suppose a program needs to perform a lot of initialization at startup. Some
of that involves network connections that are going to take several seconds each. You
can start several asynchronous operations in parallel, then perform your local initiali‐
zations, and then request the results of the network operations:
SocketAddress address = new InetSocketAddress ( args [ 0 ], port );
AsynchronousSocketChannel client = AsynchronousSocketChannel . open ();
Future < Void > connected = client . connect ( address );
ByteBuffer buffer = ByteBuffer . allocate ( 74 );
// wait for the connection to finish
connected . get ();
// read from the connection
Future < Integer > future = client . read ( buffer );
// do other things...
// wait for the read to finish...
future . get ();
// flip and drain the buffer
buffer . flip ();
WritableByteChannel out = Channels . newChannel ( System . out );
out . write ( buffer );
The advantage of this approach is that the network connections run in parallel while
the program does other things. When you're ready to process the data from the network,
but not before, you stop and wait for it by calling Future.get() . You could achieve the
same effect with thread pools and callables, but this is perhaps a little simpler, especially
if buffers are a natural fit for your application.
This approach fits the situation where you want to get results back in a very particular
order. However, if you don't care about order, if you can process each network read
independently of the others, then you may be better off using a CompletionHandler
instead. For example, imagine you're writing a search engine web spider that feeds pages
Search WWH ::




Custom Search