Futures do not run before program termination

后端 未结 3 1768
陌清茗
陌清茗 2020-12-03 18:08

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.futur         


        
3条回答
  •  渐次进展
    2020-12-03 18:50

    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:

    Test print before future
    Test print after future
    Hello future!
    

    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:

    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")
    
            Thread.sleep(3000) 
            println("Test print at the end.")
        }
    }
    

提交回复
热议问题