Java Reference
In-Depth Information
Once you get a
Future
object, you can use a polling method or a blocked waiting method to handle the result
of the asynchronous file I/O. The following snippet of code shows the polling method, where it keeps calling the
isDone()
method of the
Future
object to check if the I/O operation is finished:
while (!result.isDone()) {
// Async file I/O is not done yet. Keep working on something else
}
// We are done with the async file I/O. Get the result
int writtenNumberOfBytes = result.get();
■
Note that the call to the
Future.get()
method blocks until the result is available. the call to the
Future.isDone()
method is non-blocking.
Tip
Another version of the methods of the
AsynchronousFileChannel
class that supports asynchronous file I/O lets
you pass a
CompletionHandler
object whose methods are called when the requested asynchronous I/O operation
completes or fails. The
CompletionHandler
interface has two methods:
completed()
and
failed()
. The
completed()
method is called when the requested I/O operation completes successfully. When the requested I/O operation
fails, the
failed()
method is called. The API lets you pass an object of any type to the
completed()
and
failed()
methods. Such an object is called an
attachment
. You may want to pass an attachment such as the
ByteBuffer
or the
reference to the channel, etc. to these methods so you can perform additional actions such as reading the data from
the
ByteBuffer
inside these methods. Pass
null
as an attachment if you do not have anything useful to pass to these
methods as an attachment. Suppose you intend to use an object of the following
Attachment
class as an attachment to
you completion handler:
// Used as an attachment
public class Attachment {
public Path path;
public ByteBuffer buffer;
public AsynchronousFileChannel asyncChannel;
}
Now you can declare your completion handler class as follows:
// A class to handle completion of an asynchronous I/O operation
public class MyHandler implements CompletionHandler<Integer, Attachment> {
@Override
public void completed(Integer result, Attachment attach) {
// Handle completion of the I/O operation
}
@Override
public void failed(Throwable e, Attachment attach) {
// Handle failure of the I/O operation
}
}