Home > other >  I am doing asynchronous processing with scala, but it is not displayed
I am doing asynchronous processing with scala, but it is not displayed

Time:10-17

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
def now() = new java.util.Date();
(1 to 30).foreach(_ => Future{Thread.sleep(2000);println(now)})

I am doing asynchronous processing with scala, but it is not displayed. How can I display it in this case? No Thread.sleep please.

CodePudding user response:

No Thread.sleep please.

Without any Thread.sleep at the end of your program, your code will end after the foreach terminates and the async tasks pending will be killed. Thus very likely nothing will be printed because it doesn't take 2s to iterate over 30 items.


That being said, you could explicitly wait for the async tasks instead. With something like the following:

val tasks: Seq[Future[Unit]] = (1 to 30)
  .map(_ => Future {
    Thread.sleep(2000)
    println(now)
  })
val tasksMerged = Future.sequence(tasks)
Await.result(tasksMerged, 3.seconds)

Await will wait for async task passed in parameter to complete for up to the timeout given in parameter.

  • Related