Reputation: 1202
I am a Scala newbie trying to understand Futures. I typed in the following in the REPL:
scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global
scala> import scala.concurrent.Future
import scala.concurrent.Future
scala> val m = Future(println("Message"))
Message
m: scala.concurrent.Future[Unit] = Future(<not completed>)
scala> Future(println("Another Message"))
res4: scala.concurrent.Future[Unit] = Future(<not completed>)
Another Message
In the first case I am assigning a Future computation to a variable m
. I haven't called m
yet but the Future actually produces the "Message" string output. But I also get a Future(<not completed>)
message. What is going on here? Has the future completed or not? The string output tells me it has. Can somebody clear this up for me?
Upvotes: 0
Views: 152
Reputation: 14803
It is completed, what you see Future(<not completed>)
is just the `toString() from the Future.
try:
import scala.concurrent.ExecutionContext.Implicits.global
val f = scala.concurrent.Future{
println("Message")
}
println(f.toString())
Future execute always eagerly.
Upvotes: 1
Reputation: 1868
A Future will start executing as soon as it is created (Depending on the ExecutionContext implementation and assuming resources are available for it to run.)
The fact that you see your message printed to the console indicates your Futures have completed.
Try the following and see what happens:
Future{
Thread.sleep(5000)
println("Message")
}
Upvotes: 2