Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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/2b3c64cf1d4073a72b613fa42cedb6e431556c32
// 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.2.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