简体   繁体   English

非阻塞文件读取

[英]Non-Blocking File Reads

Is there a non-blocking file read API in java? java中是否有非阻塞文件读取API? If not would it be wise to build one in C++ and call it from a java app via JNI?如果不是,用 C++ 构建一个并通过 JNI 从 Java 应用程序调用它是明智的吗?

My original answer is now wrong, since the addition of AsynchronousFileChannel in Java 7.我原来的答案现在是错误的,因为在 Java 7 中添加了AsynchronousFileChannel

You still cannot select on a file, but there are now two asynchronous file read methods: one that takes a callback and another that returns a Future .您仍然无法选择文件,但现在有两种异步文件读取方法:一种采用回调另一种返回Future

It may be cleaner to use the callback method (and dispatch an event from the callback) than to have a dedicated thread polling a pipe.使用回调方法(并从回调中调度事件)可能比使用专用线程轮询管道更干净。

No, FileChannel does not extend SelectableChannel .不, FileChannel不扩展SelectableChannel

Probably because not all OSes support it.可能是因为并非所有操作系统都支持它。

Windows does, and in theory you could write a windows-specific C++ library and call it via JNI, but it is a lot of work to integrate this with java.nio . Windows 可以,理论上你可以编写一个特定于 Windows 的 C++ 库并通过 JNI 调用它,但是将它与java.nio集成需要做很多工作。

I would rather have a worker thread copy the file contents to a pipe and do non-blocking reads on the other end of the pipe.我宁愿让工作线程将文件内容复制到管道,并在管道的另一端进行非阻塞读取。

AsynchronousFileChannel is the right answer. AsynchronousFileChannel是正确的答案。 Yet, it does not provide an easy API.然而,它没有提供简单的 API。 It is quite verbose to use it comparing with the similar usage of java.nio.file.Files that provides simple static methods, such as: readAllLines or lines .与提供简单静态方法的java.nio.file.Files的类似用法相比,使用它是相当冗长的,例如: readAllLineslines Unfortunately Files methods are synchronous.不幸的是Files方法是同步的。

The AsyncFiles alternative from RxIo provides the corresponding non-blocking methods, with 3 different APIs: callback based, CompletableFuture and also with reactive streams .所述AsyncFiles从替代RxIo提供了相应的非阻塞方法,用3层不同的API:基于回调, CompletableFuture并且还与反应性流 Here it is an example with reactive streams :这是一个带有反应流的示例:

AsyncFiles
    .lines(path)
    .subscribe(doOnNext(line -> /*... use line from background thread ...*/));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM