Java:异步并发写入磁盘

Man*_*odi 2 java multithreading java.util.concurrent

我的主线程中有一个函数,它会将一些数据写入磁盘.我不希望我的主线程卡住(磁盘I/O的高延迟)并且创建一个新线程只是为了写入是一个矫枉过正.我决定使用ExecutorService.

ExecutorService executorService = Executors.newFixedThreadPool(3);

   Future future = executorService.submit(new Callable<Boolean>() {
    public Boolean call() throws Exception {
      logger.log(Level.INFO, "Writing data to disk");
      return writeToDisk();
    }
  });
Run Code Online (Sandbox Code Playgroud)

writeToDisk是写入磁盘的函数

这是一个很好的方式吗?有人可以提出更好的方法吗?

更新:数据大小将大于100 MB.磁盘带宽为40 MBps,因此写入操作可能需要几秒钟.我不希望调用函数卡住,因为它必须做其他工作,所以,我正在寻找一种方法来调度磁盘I/O异步执行调用线程.

我需要委派任务而忘记它!

Õzb*_*bek 8

无论如何我的代码看起来很好,我已经使用AsynchronousFileChannel了新的非阻塞IO.实现使用MappedByteBuffer通过 FileChannel.它可能会给你@Chris所说的表现.以下是一个简单的例子:

public static void main(String[] args) {
    String filePath = "D:\\tmp\\async_file_write.txt";
    Path file = Paths.get(filePath);
    try(AsynchronousFileChannel asyncFile = AsynchronousFileChannel.open(file,
                        StandardOpenOption.WRITE,
                        StandardOpenOption.CREATE)) {

        asyncFile.write(ByteBuffer.wrap("Some text to be written".getBytes()), 0);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,如果它是异步的,尝试使用资源使其在完成之前关闭似乎有点不对?main() 方法应该在 Future 返回完成之前退出(否则,它只是同步的) (3认同)