Java › I/O & NIO
How would you implement asynchronous file I/O using AsynchronousFileChannel, and how does this differ from both the classic blocking java.io model and NIO's Selector-based non-blocking channels?
AdvancedAnswer
AsynchronousFileChannel provides genuinely asynchronous file operations (read()/write() methods returning a Future, or accepting a CompletionHandler callback invoked upon completion), letting the calling thread continue with other work immediately rather than blocking OR needing to poll a Selector -- this differs from classic blocking java.io (which blocks the calling thread until the operation completes) and from Selector-based NIO channels (which are non-blocking but still require the calling thread to actively poll/select to discover when an operation has become ready), instead delegating the actual asynchronous execution to the OS/JVM's own thread pool, notifying your code via callback or Future completion once the operation genuinely finishes, appropriate for scenarios needing fully asynchronous file I/O integrated with other asynchronous application logic (like a reactive or CompletableFuture-based architecture).
AsynchronousFileChannel channel = AsynchronousFileChannel.open(Path.of("data.bin"), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
public void completed(Integer bytesRead, ByteBuffer attachment) {
System.out.println("Read " + bytesRead + " bytes asynchronously");
}
public void failed(Throwable exc, ByteBuffer attachment) {
System.err.println("Read failed: " + exc.getMessage());
}
});
// Calling thread continues immediately, notified later via the CompletionHandler callbackReal-world example A high-throughput file-processing service integrated with an existing CompletableFuture-based asynchronous pipeline uses AsynchronousFileChannel to read files without blocking any pipeline thread, fitting naturally into the surrounding fully-asynchronous architecture rather than requiring a separate dedicated thread pool just for blocking file reads.