Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using futures and Thread.sleep

Tags:

scala

future

By executing this scala code, I don't have any output in the console. (I don't really understand what is happening)

If I remove Console.println("Console.println OK!") => everything seems fine.

If I remove Thread.sleep(2000) => everything seems fine.

Do you have any ideas about this ? Thank you very much!

Clément

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.language.postfixOps

object ScalaFuture {

  def main(args: Array[String]) {

    val f: Future[String] = Future {
      Thread.sleep(2000)
      "future value"
    }

    f.onSuccess {
      case s => {
        Console.println("Console.println OK!")
        System.out.println("System.out.println OK!")
      }
    }

    Await.ready(f, 60 seconds)
  }

}
like image 678
ctamisier Avatar asked Jan 26 '15 22:01

ctamisier


People also ask

Is it a good practice to use thread sleep?

It is not a good practice to use Thread. Sleep method for synchronizing the application under test with our script. The good practice is, use explicit wait if you targeting a particular element. If you want to target the most of the elements in the page, then use Implicit wait.

Is it good to use thread sleep in Java?

Java Thread Sleep important pointsIt always pause the current thread execution. The actual time thread sleeps before waking up and start execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time but for a busy system it will be little bit more.

How long should a thread sleep?

If it is a UI worker thread, as long as they have some kind of progress indicator, anywhere up to half a second should be good enough. The UI should be responsive during the operation since its a background thread and you definitely have enough CPU time available to check every 500 ms.

How accurate is thread sleep?

Incredibly inaccurate. You have to deal with the inconsistencies of the OS process scheduler, the time spent context switching, the Java VM, etc. Well documentation is silent on its accuracy- it talks a lot about accuracy for System.


1 Answers

Your await is waiting for future to complete, which is done after 2 seconds, but it doesn't wait for onSuccess handler, which executes in another thread (similar to future), but after Await.ready(f, 60 seconds), so process exits earlier than you print something. To process it correctly - create new future for onComplete:

val f: Future[String] = Future {
  Thread.sleep(2000)
  "future value"
}

val f2 = f map { s => 
    println("OK!")
    println("OK!")    
}

Await.ready(f2, 60 seconds)
println("exit")

Results for Await.ready(f, ...):

exit
OK!
OK!

Results for Await.ready(f2, ...):

OK!
OK!
exit
like image 88
dk14 Avatar answered Sep 20 '22 04:09

dk14