Search code examples
multithreadingscalaconcurrent.futures

How to pass function output in futures and then those futures to a new function?


My Scenario is like below:

Step1: x =def sum(a,b)

Step2: Thread.sleep(1s)

Step3: y =def subtract(a,b)

Step4: Thread.sleep(2s)

Step5: On successfull completion of above steps perform z = multiple(x,y)

I need to implement this scenario using futures in Scala. Please help. I Tried this code but it is not working.

import scala.util.{Failure, Success}
def sum(a:Int ,b:Int) = a+b
def sub(c:Int, d:Int) = c-d
def mul(e: Int, f: Int) = e*f

val Sum1= Future {sum(2,3); Thread.sleep(1000)}

val SumFinal=Sum1.onComplete({
case Success(result) => println(result)
case Failure(e) => println("failed: " + e)
})

val Subt1 = Future {sub(5,3);Thread.sleep(2000)}
val SubtFinal = Subt1.onComplete({
case Success(result) => result
case Failure(e) => println("failed: " + e)
})

val Mul1= mul(SumFinal,SubtFinal)
println(Mul1)

Solution

  • Problem with your approach is that onComplete returns unit. That's why you don't get any result. So, subFimal and sumFinal has nothing in it.

    scala> def sum(a: Int, b: Int) = Future { a + b }
    sum: (a: Int, b: Int)scala.concurrent.Future[Int]
    
    scala> def sub(a: Int, b: Int) = Future { a - b }
    sub: (a: Int, b: Int)scala.concurrent.Future[Int]
    
    scala> def mul(a: Int, b: Int) = Future { a * b }
    mul: (a: Int, b: Int)scala.concurrent.Future[Int]
    
    scala> for {
         | a <- sum(2,3)
         | b <- sub(10, 7)
         | c <- mul(a, b)
         | } yield c
    res0: scala.concurrent.Future[Int] = Future(<not completed>)
    
    scala> res0
    res1: scala.concurrent.Future[Int] = Future(Success(15))