AsynchronousFileChannel CompletionHandler Read

Read a file through AsynchronousFileChannel with a CompletionHandler callback; the calling thread is never blocked waiting on the disk read to finish.

JavaResilience

Code

snippet
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;

public class AsyncFileRead {

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("note-", ".txt");
        Files.writeString(file, "async read demo", StandardCharsets.UTF_8);

        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(
                file, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            CountDownLatch done = new CountDownLatch(1);
            // 回调在完成线程触发:发起后调用线程不被 IO 阻塞
            channel.read(buffer, 0, buffer, new CompletionHandler<>() {
                @Override
                public void completed(Integer bytes, ByteBuffer buf) {
                    buf.flip();
                    System.out.println("bytes: " + bytes);
                    System.out.println(StandardCharsets.UTF_8.decode(buf));
                    done.countDown();
                }

                @Override
                public void failed(Throwable exc, ByteBuffer buf) {
                    System.out.println("failed: " + exc.getMessage());
                    done.countDown();
                }
            });
            done.await(); // 等回调落地再退出
        }
        Files.deleteIfExists(file);
    }
}

How it works

AsynchronousFileChannel CompletionHandler Read keeps everything in the class AsyncFileRead and the functions completed and failed.

Resources live in the try header, so closing is compiler-generated and exception-safe.

Applying it

The primary signature is public void completed(Integer bytes, ByteBuffer buf)

Look for the bytes:, failed: prefixes when the file runs; they tie each line to its step.

Execute the file and main walks through completed and failed, in that order.

Statements that matter

Files.writeString(file, "async read demo", StandardCharsets.UTF_8);
Path file = Files.createTempFile("note-", ".txt");
ByteBuffer buffer = ByteBuffer.allocate(16);

Interactive Tools for This Topic

FAQ

What does AsynchronousFileChannel CompletionHandler Read print when run?
Execute the whole file; each printed line is prefixed with a label like `bytes:`, `failed:`.