ZIO scala sleep method not sleeping the thread vs. using directly Thread.sleep

Viewed 524

In my existing Scala code I replaced Thread.sleep(10000) with ZIO.sleep(Duration.fromScala(10.seconds)) with the understanding that it won't block thread from the thread pool (performance issue). When program runs it does not wait at this line (whereas of course in first case it does). Do I need to add any extra code for ZIO method to work ?

Adding code section from Play+Scala code:

    def sendMultipartEmail = Action.async(parse.multipartFormData) { request =>
    .....
    //inside this controller below method is called
         def retryEmailOnFail(pList: ListBuffer[JsObject], content: String) = {
               if (!sendAndGetStatus(pList, content)) {
                  println("<--- email sending failed - retry once after a delay")
                  ZIO.sleep(Duration.fromScala(10.seconds))
                  println("<--- retrying email sending after a delay")
                  finalStatus = finalStatus && sendAndGetStatus(pList, content)
               } else {
                  finalStatus = finalStatus && true
               }
            }
   .....
    }
1 Answers

As you said, ZIO.sleep will only suspend the fiber that is running, not the operating system thread.

If you want to start something after sleeping, you should just chain it after the sleep:

// value 42 will only be computed after waiting for 10s
val io = ZIO.sleep(Duration.fromScala(10.seconds)).map(_ => 42) 
Related