这是一些 Scala cats 代码,使用IO Monad https://github.com/typelevel/cats-effect:
import java.util.concurrent.{ExecutorService, Executors}
import cats.effect.IO
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
import scala.util.control.NonFatal
object Program extends App {
type CallbackType = (Either[Throwable, Unit]) => Unit
// IO.async[Unit] is like a Future that returns Unit on completion.
// Unlike a regular Future, it doesn't start to run until unsafeRunSync is called.
def forkAsync(toRun: () => Unit)(executor: ExecutorService): IO[Unit] = IO.async[Unit] { callback: CallbackType =>
// "callback" is a function that either takes a throwable (Left) or whatever toRun returns (Right).
println("LalalaAsync: " + Thread.currentThread().getName)
executor.execute(new Runnable {
def run(): Unit = {
val nothing: Unit = toRun() // Note: This line executes the body and returns nothing, which is of type Unit.
try {
callback(Right(nothing)) // On success, the callback returns nothing
} catch {
case NonFatal(t) => callback(Left(t)) // On failure, it returns an exception
}
}
})
}
def forkSync(toRun: () => Unit)(executor: ExecutorService): IO[Unit] = IO.apply {
println("LalalaSync: " + Thread.currentThread().getName)
executor.execute(new Runnable {
def run(): Unit = {
toRun()
}
})
}
val treadPool: ExecutorService = Executors.newSingleThreadExecutor()
val mainThread: Thread = Thread.currentThread()
val Global: ExecutionContextExecutor = ExecutionContext.global
/*
Output:
1 Hello World printed synchronously from Main.main
LalalaSync: scala-execution-context-global-12
Hello World printed synchronously from thread pool.pool-1-thread-1
LalalaAsync: scala-execution-context-global-12
Hello World printed asynchronously from thread pool.pool-1-thread-1
2 Hello World printed synchronously from Global .scala-execution-context-global-12
*/
val program = for {
_ <- IO {
println("1 Hello World printed synchronously from Main." + Thread.currentThread().getName) // "main" thread
}
_ <- IO.shift(Global) // Shift to Global Execution Context
_ <- forkSync { () =>
println("Hello World printed synchronously from thread pool." + Thread.currentThread().getName) // "pool-1-thread-1" thread
}(treadPool)
_ <- forkAsync { () =>
println("Hello World printed asynchronously from thread pool." + Thread.currentThread().getName) // "pool-1-thread-1" thread
}(treadPool)
_ <- IO.shift(Global) // Shift to Global Execution Context
_ <- IO {
println("2 Hello World printed synchronously from Global ." + Thread.currentThread().getName) // "scala-execution-context-global-13" thread
}
} yield ()
program.unsafeRunSync()
}
要运行它,您需要添加:
libraryDependencies ++= Seq(
"org.typelevel" %% "cats" % "0.9.0",
"org.typelevel" %% "cats-effect" % "0.3"
),
到您的 build.sbt 文件。
注意输出:
/*
Output:
1 Hello World printed synchronously from Main.main
LalalaSync: scala-execution-context-global-12
Hello World printed synchronously from thread pool.pool-1-thread-1
LalalaAsync: scala-execution-context-global-12
Hello World printed asynchronously from thread pool.pool-1-thread-1
2 Hello World printed synchronously from Global .scala-execution-context-global-12
*/
基本上,我不明白 IO.shift(Global) 或 IO.async 是如何工作的。
例如,为什么我调用“forkAsync”后,如果不调用“IO.shift(Global)”,后续的同步IO对象都在“pool-1-thread-1”中运行。另外,在此示例中 forkAsync 和 forkSync 有什么区别?它们都在 ExecutionContext.global 中启动,然后在“pool.pool-1-thread-1”中执行 Runnable。
就像 forkAsync 和 forkSync 做完全相同的事情还是 forkAsync 做不同的事情?如果他们做同样的事情,那么将代码包装在 IO.async 中有何意义?如果他们做的不是同一件事,那么他们有何不同?