Reputation:
Given this code:
object Test {
import scala.concurrent.ExecutionContext.Implicits.global
def main(args: Array[String]): Unit = {
val f: Future[String] = Future { "Test" }
f.onComplete {
case Success(name) => println(name)
case Failure(t) => t.printStackTrace()
}
}
}
I see no output, however changing println to System.out.println works:
object Test {
import scala.concurrent.ExecutionContext.Implicits.global
def main(args: Array[String]): Unit = {
val f: Future[String] = Future { "Test" }
f.onComplete {
case Success(name) => System.out.println(name)
case Failure(t) => t.printStackTrace()
}
}
}
Also using println with a standard Thread also works:
object Test {
def main(args: Array[String]): Unit = {
val t = new Thread() {
override def run(): Unit = println("Test")
}
t.start()
t.join()
}
}
Why is this?
Upvotes: 1
Views: 905
Reputation:
So it seems that the answer lies in this answer. Scala's println is not an alias for System.out.println but Console.println which handles threads differently
Upvotes: 0
Reputation: 2331
You have to wait for the Future
's completion. So your System.out.println
version also might output or not.
object Test {
import scala.concurrent.ExecutionContext.Implicits.global
def main(args: Array[String]): Unit = {
val f: Future[String] = Future { "Test" }
f.onComplete {
case Success(name) => println(name)
case Failure(t) => t.printStackTrace()
}
Await.result(f)
}
}
Upvotes: 4
Reputation: 1766
Future and onComplete execute in separated daemon threads. When your main thread terminates (after last instruction) daemon threads also terminate. In your case they have no time to execute code. Make your main code live long, for example, Thread.sleep(100)
.
Upvotes: 4
Reputation: 14217
Because your program has exited:
def main(args: Array[String]): Unit = {
val f: Future[String] = Future { "Test" }
f.onComplete {
case Success(name) => println(name)
case Failure(t) => t.printStackTrace()
}
Thread.sleep(100)
}
Upvotes: 0