tomdavies
tomdavies

Reputation: 1976

Scala futures - which thread executes onComplete?

In Learning Akka by Jason Goodwin I read:

val future = getUsernameFromDatabaseAsync(userId)
future.onComplete(username =>
  //executed somewhere else
  println(username)
)

It's important to highlight again—the print statement will not run on the thread that registers the event. It will run somewhere else, on another thread via the ExecutionContext. Futures are always created with ExecutionContext, so you can choose where to run them.

And out of curiosity I wanted to check it myself, so I prepared a snippet:

val myFuture = Future {
  println("in future: " + Thread.currentThread().getName())
  Thread.sleep(1000)
}

myFuture.onComplete {
  case _ ⇒ println("in onComplete: " + Thread.currentThread().getName())
}

println("main: " + Thread.currentThread().getName())

Await.result(myFuture, 10 seconds)

I get the following output every time I run the snippet.

main: main
in future: ForkJoinPool-1-worker-13
in onComplete: ForkJoinPool-1-worker-13

Future and onComplete are executed on the same thread, but the book says, that onComplete might execute the callback on a different thread. How to explain it?

Upvotes: 1

Views: 1233

Answers (1)

nmat
nmat

Reputation: 7591

Because the thread that registers the event is the main thread, not the thread that runs the future. In this case, it did not ran on the thread main but instead on the thread ForkJoinPool-1-worker-13

The onComplete and the future can run on the same thread because the onComplete only begins after the future ends. The documentation just states that they will run on a thread different from the main one.

Upvotes: 3

Related Questions