Java NIO - AsynchronousFileChannel

众所周知,Java NIO 支持并发和多线程,这使我们能够同时并发处理不同的通道。因此,Java NIO 包中负责此功能的 API 是 AsynchronousFileChannel,它定义在 NIO 通道包下。因此,AsynchronousFileChannel 的限定名称是 java.nio.channels.AsynchronousFileChannel

AsynchronousFileChannel 与 NIO 的 FileChannel 类似,不同之处在于此通道允许文件操作异步执行,这与同步 I/O 操作不同,在同步 I/O 操作中,线程进入操作并等待,直到请求完成。因此,异步通道可供多个并发线程安全使用。

在异步中,请求由线程传递给操作系统的内核以完成,同时线程继续处理另一项作业。一旦内核的作业完成,它就会向线程发出信号,然后线程确认信号并中断当前作业并根据需要处理 I/O 作业。

为了实现并发,此通道提供了两种方法,一种是返回 java.util.concurrent.Future 对象,另一种是将 java.nio.channels.CompletionHandler 类型的对象传递给操作。

我们将通过示例逐一理解这两种方法。

  • Future 对象 −在此,从通道返回 Future 接口的一个实例。在 Future 接口中,有 get() 方法,该方法返回异步处理的操作的状态,在此基础上可以决定是否进一步执行其他任务。我们还可以通过调用其 isDone 方法检查任务是否完成。

示例

以下示例显示如何使用 Future 对象并异步执行任务。

package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
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.ExecutionException;
import java.util.concurrent.Future;

public class FutureObject {
   public static void main(String[] args) throws Exception {
      readFile();
   }
   private static void readFile() throws IOException, InterruptedException, ExecutionException {
      String filePath = "D:fileCopy.txt";
      printFileContents(filePath);
      Path path = Paths.get(filePath);		
      AsynchronousFileChannel channel =AsynchronousFileChannel.open(path, StandardOpenOption.READ);
      ByteBuffer buffer = ByteBuffer.allocate(400);
      Future<Integer> result = channel.read(buffer, 0); // position = 0
      while (! result.isDone()) {
         System.out.println("Task of reading file is in progress asynchronously.");
      }
      System.out.println("Reading done: " + result.isDone());
      System.out.println("Bytes read from file: " + result.get()); 
      buffer.flip();
      System.out.print("Buffer contents: ");
      while (buffer.hasRemaining()) {
         System.out.print((char) buffer.get());                
      }
      System.out.println(" ");
      buffer.clear();
      channel.close();
   }
   private static void printFileContents(String path) throws IOException {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      String textRead = br.readLine();
      System.out.println("File contents: ");
      while (textRead != null) {
         System.out.println("     " + textRead);
         textRead = br.readLine();
      }
   fr.close();
   br.close();
   }
}

输出

File contents: 
   To be or not to be?
   Task of reading file is in progress asynchronously.
   Task of reading file is in progress asynchronously.
   Reading done: true
   Bytes read from file: 19
   Buffer contents: To be or not to be? 
  • 完成处理程序

    这种方法非常简单,因为在此我们使用 CompletionHandler 接口并重写其两个方法,一个是 completed() 方法,当 I/O 操作成功完成时调用,另一个是 failed() 方法,当 I/O 操作失败时调用。在此创建一个处理程序来使用异步 I/O 操作的结果,因为一旦任务完成,只有处理程序具有可执行的函数。

示例

以下示例展示了如何使用 CompletionHandler 异步执行任务。

package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class CompletionHandlerDemo {
   public static void main (String [] args) throws Exception {
      writeFile();
   }
   private static void writeFile() throws IOException {
      String input = "Content to be written to the file.";
      System.out.println("Input string: " + input);
      byte [] byteArray = input.getBytes();
      ByteBuffer buffer = ByteBuffer.wrap(byteArray);
      Path path = Paths.get("D:fileCopy.txt");
      AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
      CompletionHandler handler = new CompletionHandler() {
         @Override
         public void completed(Object result, Object attachment) {
            System.out.println(attachment + " completed and " + result + " bytes are written.");
         }
         @Override
         public void failed(Throwable exc, Object attachment) {
            System.out.println(attachment + " failed with exception:");
            exc.printStackTrace();
         }
      };
      channel.write(buffer, 0, "Async Task", handler);
      channel.close();
      printFileContents(path.toString());
   }
   private static void printFileContents(String path) throws IOException {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      String textRead = br.readLine();
      System.out.println("File contents: ");
      while (textRead != null) {
         System.out.println("     " + textRead);
         textRead = br.readLine();
      }
      fr.close();
      br.close();
   }
}

输出

Input string: Content to be written to the file.
Async Task completed and 34 bytes are written.
File contents: 
Content to be written to the file.