Search code examples
javafilenonblocking

How to list files in directory in a non-blocking manner in Java?


Listing "files" in a directory is simple in Java using Files from the nio package:

Stream<Path> paths = Files.list(Path.of("<folder>"))

However the call to Files.list(..) is blocking. How can I list the files in a directory in a non-blocking manner?

Update

By "blocking" I mean not blocking any thread as in the context of Reactive Programming. In my case I'm using project reactor from Spring and I have a method defined like this:

public Flux<String> doStuffWithFilesInDirectory(String dir) {
    // Intellij complains that the call to "Files.list(..)" is inappropriate since it's a blocking call
    var fileStream = Files.list(Path.of(dir)); 
    return Flux.fromStream(fileStream). ..
}

Solution

  • It is in the nature of disks that they don't yield information instantly. Therefore the possible "non-blocking" solutions are

    (a) synchronous blocking execution in a separate thread, or

    (b) initiation of an asynchronous operation with some notification mechanism (callback, Future, etc.) to tell you when it's done.

    In the latter case, not only do you need this to be possible through some Java method, but the underlying OS needs to provide support. Since not all systems provide "asynchronous readdir", I suspect you won't find a Java interface either. This is an argument from general reasoning, so it's possible I'm wrong - but I wouldn't bet on it.