Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `java.nio.file.Files.createFile` a blocking call?

Does java.nio.file.Files.createFile block calling thread? If yes, what is a non blocking async alternative to create a file/directory?

I am looking for a simple solution that can work in java or scala.

like image 951
Bilal Fazlani Avatar asked Mar 26 '26 01:03

Bilal Fazlani


1 Answers

All operations in Files API are blocking. The only way to perform createFile non-blocking way is to use some kind of concurrent wrapper, that would execute that operation on other thread.

You could for example use Future from the scala's standard library:

import scala.concurrent.Future
import scala.concurrent.blocking
import scala.util.{Failure, Success}

object BlockingIOExecutionContext {
   implicit val ec: ExecutionContextExecutor = ExecutionContext.fromExecutor(
      Executors.newCachedThreadPool()
   ) // create seperate thread pool for our blocking operations
}

import BlockingIOExecutionContext._ //importing our execution context for blocking operations
// alternatively if you're doing only very few IO calls just use default ExecutionContext
// import scala.concurrent.ExecutionContext.Implicits.global

val createFileFuture: Future[Path]  = Future {
  blocking { //mark this operation as blocking
    Files.createFile(Paths.get("hello"))
  }
}

createFileFuture
  .map(_.getParent) // Future is monad, so you can use map/flatMap
  .onComplete{
     case Success(parentsPath) => /* do something when file is created */
     case Failure(exception) =>  /* do something when creation fails */
  }

When you're doing a lot of blocking IO operation it's a good idea to use a separate thread pool. Using inner blocking block is also good practice because it lets the ExecutionContext know that you're doing the blocking operation. In case you will be doing more blocking calls at once, ExecutionContext can decide to add more threads to the thread-pool.

Please check this article for more tips on using scala futures.

There are also other alternatives like cats-io, scalaz zio or monix task, but if you're not using any of these libraries already I would just stay with Future.

like image 65
Krzysztof Atłasik Avatar answered Mar 27 '26 13:03

Krzysztof Atłasik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!