Using Akka Futures

1,792 views
1,598 views

Published on

Presented at Knoldus at its Knolx session.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,792
On SlideShare
0
From Embeds
0
Number of Embeds
639
Actions
Shares
0
Downloads
24
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Using Akka Futures

  1. 1. Using Akka Futures Meetu Maltiar Principal Consultant Email: meetu@knoldus.com Twitter:@meetumaltiar
  2. 2. SIP 14There were eight different Futureimplementations:java.util.concurrent.Future akka.dispatch.Futurescala.actors.Future scalaz.concurrent.Promisescala.parallel.Future net.liftweb.actor.LAFuturecom.twitter.util.Future ...sff4s
  3. 3. Define ThemFuture and Promise are tied to each other.But they are different!A Future is a read-handle to a single valuethat may be available in a specific timeframe.A Promise is a write-handle to a singlevalue (write-once) that should be madeavailable in a specific time-frame.
  4. 4. Akka Futures definitionA Future is a data structureUsed to retrieve of some concurrentoperationThis operation is performed by an Actor or adispatcher directlyThe result can be accessed synchronously orasynchronously
  5. 5. Future has StatesA Future has three states. Initially it does not have anything, later can be a success or a failure.Pending => Success / Failure
  6. 6. Execution ContextFutures need ExecutionContext to executecallback and operationsIf we have ActorSystem in implicit scopeFuture will use default dispatcher asExecutionContext
  7. 7. Simplest Futureimport akka.actor.ActorSystemimport akka.dispatch.Futureobject SimplestFutureApp extends App { implicit val system = ActorSystem("future") val future = Future { "Hello " + " World" }}
  8. 8. PromiseThe other side of Future is a Promise.Think that the entity that creates a Future is aRequester and the one that can respond back hasa Promise.We hardly use Promise in our code, but itcompletes the understanding nonetheless!!
  9. 9. Promise Exampleobject PromiseApp extends App { implicit val system = ActorSystem("future") // create a promise val promise = Promise[String]() // get an associated future from that promise val future = promise.future // successfully fulfill that promise promise.success("promises are to be kept") // Extract the value from the Future println(future.value)}
  10. 10. Composing FuturesFutures are MonadicThere are map and flatMap methods on themWe can therefore compose them monadicallyand do asynchronous composition!!
  11. 11. Composing Exampleimport akka.actor.ActorSystemimport akka.dispatch.Futureobject CreatingFutureFromAFutureApp extends App { implicit val system = ActorSystem("future") // Future[String] val future = Future { "Hello " + " World" } // Futures are monadic so we can transform from Future[String] toFuture[Int] val anotherFuture = future map { aString => aString.length }}
  12. 12. Sync Wait On FutureThere is an Await method if we have to waitfor a Future to complete.Always avoid this. Use it as last option.Never block thats the whole point.
  13. 13. Sync Wait Exampleobject SyncWaitOnFuture extends App { implicit val system = ActorSystem("future") implicit val timeout = Timeout(50000 milliseconds) val future = Future { "Hello " + " World" } val anotherFuture = future map { aString => aString.length } // try to avoid this as much as possible val number = Await.result(anotherFuture,timeout.duration) println("String length is " + number)}
  14. 14. Async WaitFuture has several callbacks. They areonComplete: It will either be a Success or aFailureonSuccess: It will be invoked only when Futureis successfulonFailure: It will be invoked only when Futuregot a Throwable in it.
  15. 15. Async Wait Exampleimport akka.actor.ActorSystemimport akka.dispatch.Futureobject AsyncWaitOnFuture extends App { implicit val system = ActorSystem("future") val future = Future { "Hello " + " World" } val anotherFuture = future map { aString => aString.length } anotherFuture onSuccess { case number => println("String length is " + number) }}
  16. 16. Using FuturesFutures allows us to do a data flow style ofprogrammingWe know, there can be a certain type of value ina Future. So, we can do asynchronous compositionon that Future.This will result (yield) a new Future. We do notblock as we compose even when we do not have avalue yet
  17. 17. Futures ExampleWe have an identity function that sleeps for 3secondsWe want make a call to it three times gather theirresult and sum themNormal code as expected will take nine seconds :(With Futures we can do it in three seconds :)
  18. 18. Futures Example...Here is the code for identity function. Followed bycreation of three futures. // creating three futures val future1 = Future { identity(1) } val future2 = Future { identity(2) } val future3 = Future { identity(3) }def identity(number: Int): Int = { Thread.sleep(3000) number }
  19. 19. Futures Example...Now composing code using flatMap and Map // composing using map and flatMqp // not concise at all :( val oneFinalFuture = future1 flatMap { result1 => future2 flatMap { result2 => future3 map { result3 => result1 + result2 + result3 } } }
  20. 20. Futures Example...Now composing code using for expressions// for expressions are just a sugar. They are reallyconcise :) val finalFuture = for { result1 <- future1 result2 <- future2 result3 <- future3 } yield result1 + result2 + result3
  21. 21. Futures Example...Now we issue a callback to collect result finalFuture onSuccess { case sum => println("sum is " + sum) }
  22. 22. Code Sampleshttps://github.com/knoldus/AkkaKnolX
  23. 23. ReferencesViktor Klang talk on Akka And Futures at javaZone

×