Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:20
Show Gist options
  • Save dacr/3ea9b4a2edb3812a7875278eea2a24f4 to your computer and use it in GitHub Desktop.
Save dacr/3ea9b4a2edb3812a7875278eea2a24f4 to your computer and use it in GitHub Desktop.
ZIO learning - dealing with blocking operations => Nothing more to do from ZIO2 ? / published by https://github.com/dacr/code-examples-manager #66e3d0f1-9667-457e-bc95-1bcbaa1b1e61/d4d16e33444accafe36d8d60c088c82aa4689e75
// summary : ZIO learning - dealing with blocking operations => Nothing more to do from ZIO2 ?
// keywords : scala, zio, learning, blocking, synchronous, pure-functional, @testable
// publish : gist
// authors : zio
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 66e3d0f1-9667-457e-bc95-1bcbaa1b1e61
// created-on : 2021-05-14T17:17:37+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "dev.zio::zio:2.0.13"
// ---------------------
import zio.*
import java.io.IOException
import java.time.Instant
// Since ZIO2 and thanks to the new scheduler ?
// blocking operations should be automatically managed transparently by the ZIO Library !
object BlockingOperations extends ZIOAppDefault {
// ---------------------------------------------------------------------
def blockingOperation(message: String): Unit =
println(message+" "+Instant.now)
Thread.sleep(5000 + scala.util.Random.nextInt(5000))
// ---------------------------------------------------------------------
val badProgram = { // with stuck threads
def blockingTask(n: Int) = ZIO.attempt {
blockingOperation(s"BAD - running blocking task number $n")
}
ZIO.foreachPar(1 to 200)(blockingTask)
}
// ---------------------------------------------------------------------
val goodProgram = { // This time no issue, the primary pool thread is not overused !
def blockingTask(n: Int) = ZIO.attemptBlocking {
blockingOperation(s"GOOD - running blocking task number $n")
}
ZIO.foreachPar(1 to 200)(blockingTask)
}
// ---------------------------------------------------------------------
override def run = for {
_ <- badProgram.timeout(10.seconds) // Limited number of threads => slow
_ <- goodProgram.timeout(10.seconds) // spawn as many threads as requires
} yield ()
}
BlockingOperations.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment