Skip to content

Instantly share code, notes, and snippets.

@TimWSpence

TimWSpence/blockOn.scala

Last active Apr 6, 2021
Embed
What would you like to do?
Cats effect 2 nested evalOn/blockOn gotcha
import cats.implicits._
import cats.effect.{Blocker, IO, IOApp, ExitCode}
import java.util.concurrent.Executors
object Test extends IOApp {
override def run(args: List[String]): IO[ExitCode] = {
val blocker = Blocker.liftExecutorService(Executors.newCachedThreadPool())
blocker.blockOn(
for {
_ <- printThread
_ <- blocker.blockOn(printThread) >>
printThread //DANGER! This runs back on the main compute pool
//as the pool to shift back to is determined by
//the ContextShift in scope, rather than where
//it was executing before
} yield ()
).as(ExitCode.Success)
}
def printThread: IO[Unit] = IO(println(Thread.currentThread().getName()))
}
//[info] compiling 1 Scala source to /Users/tim/dev/test/target/scala-2.13/classes ...
//[info] running Test
//pool-31-thread-1
//pool-31-thread-2
//ioapp-compute-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment