I was trying to reproduce the example on new Scala 2.10 futures feature. The code I've used is:
import scala.concurrent.Future
import scala.concurrent.future
object Test {
def main(args: Array[String]) {
println("Test print before future")
val s = "Hello"
val f = future {s + " future!"}
f onSuccess {case v => println(v)}
println("Test print after future")
}
}
Instead of printing:
Test print before future
Hello future!
Test print after future
It simply prints:
Test print before future
Test print after future
Any idea of why I have this behaviour? My version of scala compiler is 2.10.0-20120507.
The issue is that you're executing that as a standalone program, whose main thread is terminating before one of the worker threads can execute the "Hello future!"
println
. (The threads that the new futures library spawns are daemon threads).You can also use the
Await
object (also inscala.concurrent
) to wait until the futuref
is completed:This can print:
Or, it can print "Hello future!" before "Test print after future" depending on the thread schedule.
Likewise, you can force the main thread to wait until
f
is completed before the lastprintln
as follows:Which would print:
However, note that when you use
Await
, you're blocking. This of course makes sense to make sure that your main application thread doesn't terminate, but generally shouldn't be used unless necessary otherwise.(The
Await
object is a necessary escape hatch for situations like these, but using it throughout application code without concern for its semantics can result in slower, less-parallel execution. If you need to ensure that callbacks are executed in some specified order, for example, there are other alternatives, such as theandThen
andmap
methods onFuture
.)I just want to add that in general there is another possibility that futures are not running: Hitting the thread pool limit.
In your case it probably was simply a timing issue as others have pointed out, but as future reference consider this example:
On my machine the default global execution context has just 4 Threads. Since the worker threads are busy executing the 4 non-sense futures, the future below will never run. This is why one should be careful with the default execution context and it is best to specify one's own execution context when dealing with multiple (really) long running futures.
I think that problem here is timing. Most probably your future code is running in separate deamon thread. I think that application finishes very fast and this deamon thread do not have enough time to execute properly (application does not wait for deamon threads to finish). But this also very system-dependent behavior. For me it prints:
and then exits (I'm using Scala 2.10.0-M3). You can try following in order to test it - just put main execution thread in sleep for several seconds and see whether
Hello future!
is printed: