Question

In the following,it run a calcuation after delay 2 seconds, but when run the app, it never exit. What is the code blocking the app to exit?

object Test extends App{
   import scala.concurrent._
   import java.util._
   import java.util.concurrent.{ TimeUnit }
   val timer = new java.util.Timer()
   def timeoutFuture[A](v: A, delay: Long, unit: TimeUnit): Future[A] = {
    println("inner")
    val p = Promise[A]()
    println("inner")
    timer.schedule(new java.util.TimerTask {
      def run() {
        p.success(v)
      }
    }, unit.toMillis(delay))
    println("inner")
    p.future
   }
   println("begin")
   val x1=timeoutFuture[Int](1+1,2,TimeUnit.SECONDS)
   println("end")
   println("quit")
}
Was it helpful?

Solution

val timer = new java.util.Timer() will start a TimerThread (which extends a standard Java thread and is implemented as an infinite loop), which is running in the background and prevent your application from exiting.

You can run System.exit(0) at the end of your script to stop all the background threads.

Also have you considered using Akka scheduler instead of Java Timer?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top