Wednesday, April 15, 2015

Scala Futures

A nice walkthrough of Futures what they are in Scala and how to use them
http://docs.scala-lang.org/overviews/core/futures.html

In Eclipse the following Worksheet code can be executed based on the examples. You can run in a worksheet to see the async calls all come back at the same time.


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

object Actors {
  println("Actors----")                           
  val r = scala.util.Random                       
  
  def getAmount(): Int = {
    Thread.sleep(3000)
    r.nextInt(10)
  }                                               
  println("Lets do three getAmount which take 3 seconds each")
                                                  
  val f1: Future[Int] = future {
    getAmount()
  }
  val f2: Future[Int] = future {
    getAmount()
  }
  val f3: Future[Int] = future {
    getAmount()
  }

  println("OnComplete starts")                    
  f1 onComplete {
    case Success(ans) => println(s"1.ASYNC COMPLETED : ${ans}")
    case Failure(t) => println(s"ERROR : ${t}")
  }
  f2 onComplete {
    case Success(ans) => println(s"2.ASYNC COMPLETED : ${ans}")
    case Failure(t) => println(s"ERROR : ${t}")
  }
  f3 onComplete {
    case Success(ans) => println(s"3.ASYNC COMPLETED : ${ans}")
    case Failure(t) => println(s"ERROR : ${t}")
  }
  
  println("Wait")                                 
  Thread.sleep(4000)                              
  println("Wait Over")                            
  println("Doing syncronously takes long")        
  println(getAmount())                           
  println(getAmount())                            
  println(getAmount())                            
  
  
  println("Composition----Callback")              
  val amount = future {
    getAmount()
  }
  Thread.sleep(4000)
  amount onSuccess { case a =>
    val purchase = future {
      if (a >= 5) "BUY"
       else "SELL"
    }
    purchase onSuccess {
      case a => println(s"purchase [${a}]")
    }
  }
  Thread.sleep(1000)                              

  println("Composition----Map")                   
  val amount2 = future {
    getAmount()
  }
  Thread.sleep(4000)
  
  val purchase = amount2 map { a =>
    if (a >= 5) "BUY"
    else "SELL"
  }
  purchase onSuccess {
    case a => println(s"purchase [${a}]")
  }
  
  println("End----")
}

No comments:

Post a Comment