With the recent, vivid trend towards multicore hardware and the ever growing application requirements, concurrency is no more a niche area it used to be, and is slowly becoming a norm. In this talk, we will talk about promises/futures, one of the concurrency models that has risen to the occasion. We will look at what they are, how they're implemented and used in Java and Javascript. We will see how Scala, with its functional paradigm and greater abstraction capabilities, avoids "callback hell" typically associated with the model, allows writing of concurrent code in "direct style", and thereby greatly reduces the cognitive burden, allowing you to focus on application logic better.
Semelhante a Promise of a better future by Rahul Goma Phulore and Pooja Akshantal, ThoughtWorks - presented at Pune Scala Symposium 2014, ThoughtWorks (20)
3. What we are going to talk about
• How concurrency and parallelism are different
ideas
• Why concurrency is important
• Futures and promises
• DEMO!
• Pitfalls
4. Concurrency ≠ Parallelism
Concurrency is a program-
structuring technique in which
there are multiple threads of
control
A parallel program is one that
uses a multiplicity of
computational hardware (e.g.
multiple processor cores)
Structure Execution
Dealing with lots of things at
once
Doing lots of things at once
10. Future ≈ Cheap thread
• Futures are multiplexed dynamically onto
threads as needed.
• Managed by ExecutionContext.
• It’s practical to have hundreds of thousands
going at once.
• Spawn away!
12. Async and non-blocking
• Goal: Do not block current thread while
waiting for the result of the future.
• Callbacks:
– Register callback which is invoked asynchronously
when future is completed
– Async computations do not block
14. There is a solution!
• Higher-order functions / combinators
• for-comprehensions
• Other abstractions
15. Running example
• Collect statistics for a
facebook page
• For every post on the
page:
– Collect all likes
– Collect all comments
• Aggregate results into popularity score
17. Other parallels
• Error recovery combinators
– recover
– recoverWith
• Collection operations
– map: (Seq[A], A ⇒ B) ⇒ Seq[B]
mapF: (Seq[A], A ⇒ Future[B]) ⇒ Future[Seq[B]]
– filter: (Seq[A], A ⇒ Boolean) ⇒ Seq[A]
filterF: (Seq[A], A ⇒ Future[Boolean]) ⇒ Future[Seq[A]]
18. Pitfalls
• Interactions with thread-unsafe libraries
• ThreadLocal variables
• Retries, time-outs not very natural
• Simpler than other concurrency models in
many ways, but still incur some cognitive cost
19. Credits
• Heather Miller, for her material on
relationship between futures and promises
• Simon Marlow and Rob Pike, for their
material on concurrency and parallelism
• Josh Suereth, for his Github example
(Inspiration for our facebook example)
• Scala, Play, and Akka teams for all their
amazing work