0

scala 2.11.7 in use.

A weird problem occurred on the code below. Calling Future#onSuccess didn't print out anything, but replacing it to Await#result outputted 3 as expected.

import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration._

object FutureTest extends App {

  val f1 = Future {
    Thread.sleep(1000)
    1
  }

  val f2 = Future {
    Thread.sleep(2000)
    2
  }

  val f = for {
    v1 <- f1
    v2 <- f2 
  } yield v1 + v2

  f onSuccess { case v => println(v) } // Why did nothing happen here?

  // println(Await.result(f, Duration.Inf)) // => 3
}

@EDIT

Future runs as daemon thread - JVM can exit before it completes.

sof
  • 9,113
  • 16
  • 57
  • 83
  • 1
    http://stackoverflow.com/questions/31900681/the-future-is-not-complete – Michael Zajac Sep 07 '15 at 16:09
  • 1
    Basically your application shuts down in first case sooner than future completes. I had this same "issue" once upon a time :) – dmitry Sep 07 '15 at 16:44
  • 1
    Look into Scalaz `Task` or Scala `Async` - working with Scala `Future` is too primitive. –  Sep 07 '15 at 16:49

0 Answers0