4

This works as expected:

object Planexecutor extends App {    
  import scalaz.concurrent.Future
  import scala.concurrent.duration._

  val f = Future.apply(longComputation)
  val result = f.run
  println(result)
}

This does not:

object Planexecutor extends App {    
  import scalaz.concurrent.Future
  import scala.concurrent.duration._

  val f = Future.apply(longComputation).timed(1.second)
  val result = f.run
  println(result)
}

In the first case, the application exits normally whereas in the second case it does not. However, both versions properly print out the result value.

Is this a bug or is there something I am not understanding?

jedesah
  • 2,983
  • 2
  • 17
  • 29

1 Answers1

5

The problem is with the threadpool that timed is using. If you look at the source you can see that it's using a default of Strategy.DefaultTimeoutScheduler which is just a generic java threadpool and it's threads aren't set to daemon status. The default threadpool of Future.apply does have daemon status on it's thread set so the JVM will shutdown properly. To fix this you can manually shutdown the thread pool after your code finishes:

  scalaz.concurrent.Strategy.DefaultTimeoutScheduler.shutdown()

or you could pass a different threadpool:

  val newTimeOutScheduler = Executors.newScheduledThreadPool(1, new ThreadFactory {
    val defaultThreadFactory = Executors.defaultThreadFactory()
    def newThread(r: Runnable) = {
      val t = defaultThreadFactory.newThread(r)
      t.setDaemon(true)
      t
    }
  })

  val f = Future.apply(longComputation).timed(1.second)(newTimeOutScheduler)

you can also manage this via implicits so you don't have to manually add this:

  implicit val newTimeOutScheduler = Executors.newScheduledThreadPool(1, new ThreadFactory {
    val defaultThreadFactory = Executors.defaultThreadFactory()
    def newThread(r: Runnable) = {
      val t = defaultThreadFactory.newThread(r)
      t.setDaemon(true)
      t
    }
  })

  val f = Future.apply(longComputation).timed(1.second)

UPDATE: It's a pretty simple fix so I made a pull request.

Noah
  • 13,821
  • 4
  • 36
  • 45