最佳答案
Files API中的所有操作都被阻止.执行createFile非阻塞方式的唯一方法是使用某种并发包装器,该包装器将在其他线程上执行该操作.
原文链接:https://www.f2er.com/java/532926.html例如,您可以使用scala标准库中的Future:
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 */
}
当您执行大量阻塞IO操作时,最好使用单独的线程池.
使用内部阻塞块也是一种好习惯,因为它使ExecutionContext知道您正在执行阻塞操作.万一您一次要执行更多阻塞调用,ExecutionContext可以决定向线程池添加更多线程.
请检查此article,以获取有关使用Scala期货的更多提示.
还有其他选择,例如cats-io,scalaz zio或monix task,但是如果您尚未使用这些库中的任何一个,我将只使用Future.