Manu Chadha
Manu Chadha

Reputation: 16755

Multiple onCompletion works in Futures in Scala

While experimenting with Futures in Scala, I notice that multiple calls to OnCompletion works!

Question 1 - Obviously, I shouldn't write the code this way but I wonder if the compiler should raise an error in this case?

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure,Success}

object ConcurrencyExample extends App {
  val time = System.currentTimeMillis()

  println("looking at inventory")
  //create code we want to execute concurrently
  val f: Future[Int] = Future //or just f = Future
  {
    println("add item to shopping basket")
    Thread.sleep(30) //simulate backend process delay
    println("Item added")
    1 //simulate the no. of items in basket

  }

//this works
  f onComplete (x => println("on complete1 " + x))
//and this too
  f onComplete {
    case Success(value) => println("on complete2 size of basket" + value)
    case Failure(e) => println(e)
  }

//this is called as well though I do not see problem in this as I can segregate the code for completion, success and failure
  f onSuccess {
    case v => println("on success size of basket"+v)
  }

  f onFailure {
    case e => println("on failure. Reason"+e)
  }


  for (i<- 1 to 5)
  {
    println("looking at more items in inventory ")
    Thread.sleep(10)
  }
  Thread.sleep(500)
}

//result

looking at inventory
add item to shopping basket
looking at more items in inventory 
Item added
on success size of basket1
**on complete2 size of basket1
on complete1 Success(1)**
looking at more items in inventory 
looking at more items in inventory 
looking at more items in inventory 
looking at more items in inventory 

Question 2 - Is the order of execution of multiple callback (of same type) deterministic?

Upvotes: 3

Views: 1817

Answers (1)

vvg
vvg

Reputation: 6395

Next quote from documentation may answer both your questions:

The onComplete, onSuccess, and onFailure methods have result type Unit, which means invocations of these methods cannot be chained. Note that this design is intentional, to avoid suggesting that chained invocations may imply an ordering on the execution of the registered callbacks (callbacks registered on the same future are unordered).

a1: you can register as many callbacks as you want

a2: they will execute in "random" order.

Upvotes: 10

Related Questions