Last active
April 28, 2023 13:42
-
-
Save TimWSpence/c0879b00936f495fb53c51ef15227ad3 to your computer and use it in GitHub Desktop.
Cats effect 2 nested evalOn/blockOn gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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