Daniel Wu
Daniel Wu

Reputation: 6003

why the main app doesn't exit when calling a timer.schedule

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")
}

Upvotes: 3

Views: 1872

Answers (1)

Norbert Radyk
Norbert Radyk

Reputation: 2618

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?

Upvotes: 2

Related Questions