Search code examples
javaspring-webfluxproject-reactorreactor

Does doFinally execute on the same thread in Reactor


Does doFinally execute on the same thread? Will below code block the main thread?

mono
.map(fileName -> asyncDownloadFile(fileName, folderName))
.doFinally(v -> {
    FileUtils.cleanDirectory(folderName); // this method is blocking
});

if so what is the best way to execute cleanDirectory in a separate thread in doFinally?


Solution

  • Wrap the blocking call in a Runnable and run it on a separate thread:

    Runnable task = () -> {FileUtils.cleanDirectory(folderName)};
    
    Mono<Object> cleanDirPromise = Mono.fromRunnable(task);
    
    mono
    .map(fileName -> asyncDownloadFile(fileName, folderName))
    .doFinally(v -> {
        cleanDirPromise.subscribeOn(Schedulers.parallel()).subscribe();
    });
    

    Note: This will essentially be a fire-and-forget call where you won't really care about the result of cleanDirPromise.