bsky
bsky

Reputation: 20222

Future declaration seems independent from promise

I was reading this article http://danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html and I was looking at this code:

object Government {
  def redeemCampaignPledge(): Future[TaxCut] = {
    val p = Promise[TaxCut]()
    Future {
      println("Starting the new legislative period.")
      Thread.sleep(2000)
      p.success(TaxCut(20))
      println("We reduced the taxes! You must reelect us!!!!1111")
    }
    p.future
  }
}

I've seen this type of code a few times and I'm confused. So we have this Promise:

val p = Promise[TaxCut]()

And this Future:

Future {
  println("Starting the new legislative period.")
  Thread.sleep(2000)
  p.success(TaxCut(20))
  println("We reduced the taxes! You must reelect us!!!!1111")
}

I don't see any assignment between them so I don't understand: How are they connected?

Upvotes: 1

Views: 66

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

I don't see any assignment between them so I don't understand: How are they connected?

A Promise is a one way of creating a Future.

When you use Future { } and import scala.concurrent.ExecutionContext.Implicits.global, you're queuing a function on one of Scala's threadpool threads. But, that isn't the only way to generate a Future. A Future need not necessarily be scheduled on a different thread.

What this example does is:

  1. Creates a Promise[TaxCut] which will be completed sometime in the near future.
  2. Queues a function to be ran inside a threadpool thread via the Future apply. This function also completes the Promise via the Promise.success method
  3. Returns the future generated by the promise via Promise.future. When this future returns, it may not be completed yet, depending on how fast the execution of the function queued to the Future really runs (the OP was trying to convey this via the Thread.sleep method, delaying the completion of the future).

Upvotes: 3

Related Questions