Reputation: 1868
Here's the code snippet:
object Test {
def main(args: Array[String]): Unit = {
// MARK: parallelization
val pool = Executors.newFixedThreadPool(3)
implicit val xc = ExecutionContext.fromExecutorService(pool)
var taskQueue = new ArrayBuffer[Future[Unit]]()
for (i <- 0 until 10) {
try {
taskQueue += Future {
print(s"in_${i}\n")
Thread.sleep(1000)
}
} catch {
case t: Throwable => {
print(t)
}
}
}
val importTasks = Future.sequence(taskQueue)
importTasks.onSuccess { case res => print("finishOnSuccess") }
Await.result(importTasks, Duration.Inf)
}
}
it will hang forever after all jobs are executed with the following output:
in_1 in_2 in_0 in_4 in_3 in_5 in_8 in_6 in_7 in_9 finishOnSuccess
I tried to call System.exit(0)
at the end of main
method but still no use. Any suggestions? Thanks!
Upvotes: 1
Views: 108
Reputation: 14217
You need to shutdown
ExecutorService
of pool
by pool.shutdown()
after Await
. Since the newFixedThreadPool
is creating non-daemon thread by defaultThreadFactory.
and this Post explain more about Daemon thread and Non-Daemon thread:
What is Daemon thread in Java?
Upvotes: 2