Java NIO 提供了 AsynchronousChannel 接口,用于支持异步 I/O 操作。与传统的阻塞和非阻塞 I/O 模型不同,AsynchronousChannel 实现了异步非阻塞的 I/O 模型,这意味着 I/O 操作可以在后台进行,当操作完成后,系统会通知应用程序或执行回调。

主要的 AsynchronousChannel 实现
  • AsynchronousSocketChannel: 异步 TCP 套接字通道,支持异步的网络读写操作。
  • AsynchronousServerSocketChannel: 异步服务器套接字通道,支持异步的客户端连接接受操作。
  • AsynchronousFileChannel: 异步文件通道,支持异步文件读写操作。
基本概念和操作

AsynchronousChannel 允许你在进行 I/O 操作时,不必等待操作完成,而是可以立即返回并继续执行其他任务。当 I/O 操作完成时,系统会调用指定的回调函数或者通过 Future 对象通知应用程序。

操作方式

AsynchronousChannel 支持两种主要的操作模式:

  1. 基于 Future 的操作:
  • 使用 Future 对象表示异步操作的结果,主线程可以继续执行其他任务,稍后通过调用 Future.get() 来获取操作结果。
  • 例如:AsynchronousSocketChannel.read(ByteBuffer) 返回一个 Future<Integer>,表示读取操作的结果。
  1. 基于回调的操作:
  • 通过提供 CompletionHandler 回调接口,异步操作完成后会自动调用该回调方法,处理结果或错误。
  • 例如:AsynchronousFileChannel.read(ByteBuffer, long, A, CompletionHandler<Integer,? super A>) 使用 CompletionHandler 处理文件读取操作的结果。
使用示例
1. 异步文件读取操作示例

以下示例演示了如何使用 AsynchronousFileChannel 进行异步文件读取操作,并通过 CompletionHandler 来处理读取完成后的结果。

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.io.IOException;

public class AsynchronousFileReadExample {

    public static void main(String[] args) {
        Path path = Paths.get("example.txt");

        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            // 方式 1: 使用 Future
            Future<Integer> result = fileChannel.read(buffer, 0);

            while (!result.isDone()) {
                System.out.println("Reading file in progress...");
            }

            Integer bytesRead = result.get();
            System.out.println("Bytes read: " + bytesRead);

            // 方式 2: 使用 CompletionHandler
            fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("Bytes read: " + result);
                    attachment.flip();
                    byte[] data = new byte[attachment.limit()];
                    attachment.get(data);
                    System.out.println("File content: " + new String(data));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.err.println("Read operation failed: " + exc.getMessage());
                }
            });

            // 等待回调完成
            Thread.sleep(1000);
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
2. 异步套接字通道操作示例

下面的示例展示了如何使用 AsynchronousSocketChannel 来实现异步的 TCP 客户端,连接到服务器并发送数据。

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;
import java.io.IOException;

public class AsynchronousSocketChannelExample {

    public static void main(String[] args) {
        try {
            AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
            InetSocketAddress hostAddress = new InetSocketAddress("localhost", 5000);

            // 方式 1: 使用 Future 连接
            Future<Void> future = socketChannel.connect(hostAddress);
            future.get(); // 阻塞等待连接完成

            // 方式 2: 使用 CompletionHandler 连接
            socketChannel.connect(hostAddress, null, new CompletionHandler<Void, Void>() {
                @Override
                public void completed(Void result, Void attachment) {
                    System.out.println("Connected to server!");

                    // 写数据到服务器
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    buffer.put("Hello Server!".getBytes());
                    buffer.flip();

                    // 异步写数据
                    socketChannel.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            System.out.println("Message sent to server!");
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            System.err.println("Failed to send message: " + exc.getMessage());
                        }
                    });
                }

                @Override
                public void failed(Throwable exc, Void attachment) {
                    System.err.println("Failed to connect to server: " + exc.getMessage());
                }
            });

            // 主线程继续执行其他任务...

            // 确保主线程不立即退出
            Thread.sleep(5000);
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
适用场景
  • 高并发网络服务: 异步 I/O 非常适合需要处理大量并发连接的网络服务器,如聊天服务器、Web 服务器等。
  • 后台文件处理: 异步文件 I/O 可以用于不影响主线程执行的文件操作,适合需要处理大文件或大量文件 I/O 的应用。
总结

AsynchronousChannel 提供了异步非阻塞的 I/O 操作方式,适用于高性能和高并发的场景。通过 FutureCompletionHandler,开发者可以在 I/O 操作完成后进行相应的处理,而无需阻塞线程等待 I/O 操作完成。