Reputation: 1747
Use future in repl:
scala> val a=Future{1}
a: scala.concurrent.Future[Int] = Future(<not completed>)
scala> a.value
res0: Option[scala.util.Try[Int]] = Some(Success(1))
return Some(Success(1))
Use it in IDEA:
object A extends App{
val a=Future{1}
println(a.value)
}
return None:
"C:\Program Files\Java\jdk1.8.0_201\bin\java.exe"...
None
Why?There is no something like Thread.Sleep,so in any situation,I think the Future will return immediately,give me Some(Successs(1))
Thanks!
Upvotes: 0
Views: 43
Reputation: 40500
The Future
is executed asynchronously. It is submitted to the thread pool queue, where one of the available threads picks it up eventually, and executes.
When you are running in repl, somewhere (during IO probably), the current thread looses control, the context switches, and another thread gets a chance to pick up the task from the queue and complete it.
When running it as a program, the a.value
is executed immediately after a=Future
, in the same thread, the asynchronous task is still sitting in the queue.
Upvotes: 1