2
import java.util.concurrent.Executors

import scala.concurrent._
import scala.util.{Failure, Success}
import scala.concurrent.duration.DurationInt
import scala.language.postfixOps

object Test extends App {

  println("start")

  implicit val ec: ExecutionContextExecutorService = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(10))

  val future: Future[Unit] = Future {
    println(s"future")
    Thread.sleep(1000)
  }

  future.onComplete({
    case Success(x) => println("Success")
    case Failure(x) => println("Failure")
  })

  Await.result(future, 10 seconds)

  println("finish")

}

and the ouput is:

start
future
finish
Success

... but the program never ends

This is happening because I am using other Execution Context implementation, when I use scala.concurrent.ExecutionContext.Implicits.global everything is fine.

What am I missing?

coffee
  • 3,048
  • 4
  • 32
  • 46

1 Answers1

2

The reason the program does not shut down is because of the way the ExecutionContext was initialized:

ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(10))

This creates a pool of 10 threads via the defaultThreadFactory which creates non daemon threads:

Each new thread is created as a non-daemon thread

Unterminated non-daemon threads will prevent the JVM from exiting. You either need to provide a ThreadFactory that creates daemonthreads, or manually call shutdown on the Executor you created your ExecutionContext from.

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106