This post not only covers “onSuccess” method on a “Future”, but also clarifies the difference between executing a closure and a function definition. Is anything wrong with the following Scala concurrency code?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import scala.concurrent.ExecutionContext.Implicits.global //thread pool execution context import scala.concurrent.{Await, Future} import scala.actors.threadpool.AtomicInteger import scala.concurrent.duration._ // 5 seconds object SimpleFuture extends App { val counter = new AtomicInteger //can succeed or fail val futureInc = Future { Thread.sleep(2000) // 2000ms processing time println("Incrementing .....") counter.incrementAndGet() } val f1: Future[Int] = futureInc val f2: Future[Int] = futureInc f1.onSuccess { case val1 => { println("val1 = " + val1) f2.onSuccess { case val2 => println("val2 = " + val2) println("Sum of generated numbers = " + (val1 + val2)) } } } Thread.sleep(5000) } |
Output:
|
1 2 3 4 5 6 |
Incrementing ..... val1 = 1 val2 = 1 Sum of generated numbers = 2 |
“ … Read more ›...