TheWolf
TheWolf

Reputation: 1695

Non-Blocking File Reads

Is there a non-blocking file read API in java? If not would it be wise to build one in C++ and call it from a java app via JNI?

Upvotes: 9

Views: 5663

Answers (3)

Miguel Gamboa
Miguel Gamboa

Reputation: 9343

AsynchronousFileChannel is the right answer. Yet, it does not provide an easy 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. Unfortunately Files methods are synchronous.

The AsyncFiles alternative from RxIo provides the corresponding non-blocking methods, with 3 different APIs: callback based, CompletableFuture and also with reactive streams. Here it is an example with reactive streams:

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

Upvotes: 0

finnw
finnw

Reputation: 48619

My original answer is now wrong, since the addition of AsynchronousFileChannel in Java 7.

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.

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.

Upvotes: 23

finnw
finnw

Reputation: 48619

No, FileChannel does not extend 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.

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.

Upvotes: 7

Related Questions