简体   繁体   中英

Twitter Futures - how are unused futures handled?

So I have a api in Scala that uses twitter.util.Future

In my case, I want to create 2 futures, one of which is dependent on the result of the other and return the first future

def apiFunc(): Future[Response]={
  val future1 = getFuture1()
  val future2 = future1 map {
     resp => processFuture1Resp(resp)
  } 

  future1
}

So in this case, future2 is never consumed and the api returns the result of future1 before future2 is completed

My question is - will future2 run even though the api has returned?

My understanding is that futures spawn threads, but I am unsure if that thread will be terminated after the return of the main thread

I guess a different way to ask this is - Will a twitter.util.future always be executed?

If you want to chain two futures where one of them processes the result of the other (and return a future), you can use a for comprehension:

  def getFuture1() = {
    println("Getting future 1...")
    Thread.sleep(1000)
    Future.successful("42")
  }

  def processFuture1Resp(resp: String) = {
    println(s"Result of future 1 is: ${resp}")
    "END"
  }

  def apiFunc(): Future[String]={
    for {
      res1 <- getFuture1()
      res2 <- Future(processFuture1Resp(res1))
    } yield res2
  }

  def main(args: Array[String]) {
    val finalResultOfFutures: Future[String] = apiFunc()
    finalResultOfFutures
    Thread.sleep(500)
  }

This will print:

Getting future 1...    
Result of future 1 is: 42

The value finalResultOfFutures will contain the result of chaining both futures, and you'll be sure that the first future is executed before the second one. If you don't wait for the execution of finalResultOfFutures on the main thread (commenting the last sleep function of the main thread), you will only see:

Getting future 1...

The main thread will finish before the second future has time to print anything.

Another (better) way to wait for the execution of the future would be something like this:

val maxWaitTime: FiniteDuration = Duration(5, TimeUnit.SECONDS)
Await.result(finalResultOfFutures, maxWaitTime)

Await.result will block the main thread and waits a defined duration for the result of the given Future. If it is not ready or completes with a failure, Await.result will throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM