SlideShare a Scribd company logo
1 of 41
Composable Futures
  with Akka 2.0
    by Mike Slinn

     #akkafuture

    at Googleplex
    April 18, 2012
Outline


•   Concurrency 101
•   Akka concurrency options
•   Foundation: java.util.concurrent
•   Definitions
•   Functional programming and concurrency
•   Performance tuning
•   3 demos
Available from
slinnbooks.com
About Mike Slinn

• Principal at Micronautics Research
• Hands-on architect, mentor, trainer
• Interim technical leader for companies in
    transition
•   Recognized in US Federal court as a
    software expert
•   Author of Composable Futures with Akka 2.0
•   Interested in artificial personality
•   Coordinator of BASE and Scala for Startups
Horizontal Scale – More Cores
Threads

• Independent, heap-sharing execution
    contexts
•   Scheduled by the operating system
•   Creation is expensive in Java
•   Pools create additional complexity
•   Cache coherency issues
Multithreading and Callbacks
Standard Thread Pools

• Cached
• Fixed
• Scheduled
• Single
• Single scheduled
• Fork / join (JDK 7 and improved jsr166y)
• Variants with/without daemon threads often
 required
Concurrency Definitions

• Concurrent tasks are stateful, often with
    complex interactions
•   Parallelizable tasks are stateless, do not
    interact, and are composable
java.util.concurrent

• Akka is built on top of
    java.util.concurrent (j.u.c.)
•   Futures are designed to be used with a
    Callable, which returns a result
•   Executors contain factories and utility
    methods for concurrent classes
•   ExecutorService.shutdown()
j.u.c. Primitives

• Callable, Runnable
• Threads, thread pools and Executors
• CompletionService, CountDownLatch,
    concurrent collections, CyclicBarrier,
    Phaser, Semaphone, TimeUnit
•   Primitive Future<T>
j.u.c. Is Too Hard To Use

• Multithreaded programs tend to be buggy
     o Non-determinism caused by concurrent threads
       accessing (shared) mutable state.
• Actors and transactions manage state and
    are therefore not the first solution you should
    consider.
•   To get deterministic processing, avoid
    (shared) mutable state.
Concurrency Hazards

• CPU registers
• L1, L2 and L3 caches
  o L1 cache for each core
  o L2 cache shared by pairs of cores
  o L3 cache shared by all cores
• Processors are different, so a program may
 run fine on one system but fail on another
Cache Line Ping-Pong
Result Array (Scala)
var data = Array(threadCount)
Cache Line Ping-Pong

• 8.5 ms vs. 830 ms (C# code)
• Multicore efficiency: 10%
MESI Protocol

• Each processor cache can be in one of four
    states:
    o   Modified
    o   Exclusive
    o   Shared
    o   Invalid
• When one core writes to main memory, the
    entire cache block is marked invalid
•   Block sizes depend on processor (64 bytes,
    128 bytes, etc.)
Cache Line Ping-Pong

• Manifests even when external state is not
  shared
  o One or more cores repeatedly invalidate caches of
    the other cores, even while accessing isolated state.
  o The other cores must read data from main memory
    instead of their local cache
  o Slows program up to two orders of magnitude.
Cache Line Ping-Pong
1.j.u.c. solution:
@volatile var data = Array(threadCount)
synchronized(data) {
  data(i) = whatever
}

2.Do not access external mutable state from a
   thread
3. Use functional programming techniques
Large, Realtime Guidelines by Prismatic

• Use functional programming to build fine-
    grained, flexible abstractions.
•   Compose these abstractions to express
    problem-specific logic.
•   Prefer lightweight, composable custom
    abstractions rather than monolithic
    frameworks (e.g., Hadoop).
Functional-Style Pipelines

• *nix pipes (linear)

• Scala parallel collections & Akka composable
  futures (parallel)
Better Concurrency Options

• Ordered by increasing complexity & overhead
   o   j.u.c.
   o   Scala parallel collections
   o   Akka futures* (Java & Scala)
   o   Akka/Scala dataflow*
   o   Akka actors (Java & Scala)
• You can mix & match the above
* Covered in my book:
  “Composable Futures with Akka 2.0”
 Covered in my April 23 InfoQ article.
Scala Parallel Collections

• Very easy to use
• Not configurable
• Block
• Composable
• Easy to reason with
• Benefits from ongoing improvements to
 ForkJoinPool
  o (Scala uses jsr166y)
Akka and j.u.c.
Akka Dispatchers and j.u.c.
Akka/Scala Dataflow*

• Callable from Scala only
• Has peculiar operators
• Easy to reason with
• Designed for shared mutable state
• Dataflow blocks are composable
• Good for coordination of asynchronous
    activities
•   Good for consolidating multiple sources of
    data
Akka Actors

• Callable from Java & Scala
• Over-hyped (remember EJB 2?)
• Most complex option
• Distributed concurrency: can scale beyond
    one motherboard
•   Not composable
•   Can be difficult or impossible to prove correct
•   This should be your last option to consider
Akka Futures

• Callable from Java & Scala
• More flexible than Scala parallel collections
• Much less complex than Akka actors
• Composable
• Easy to reason with
• Payloads (Callables) should not have side
    effects
•   Should not be used with shared mutable
    state
What is a Future?

• Holder for a result that will become available
    at a later time.
•   Each future is backed by a thread.
•   If the computation fails, the future can also
    hold the resulting Throwable.
•   Write-once (immutable)
•   Akka and Twitter futures are composable and
    transformable (j.u.c. futures are not)
Akka & Twitter Futures

• Manage concurrency
• Higher-level than j.u.c. primitives
• Immutable
• Inexpensive
• Can be preset to a value or exception when
    created.
•   Blocking and non-blocking operations
    supported
Composable Futures

• Operations on a future or a collection of
    futures can be chained together without
    blocking
•   Transformations such as map and flatMap
    can be applied to a single future
•   Collections of futures can be manipulated
Akka Future Operations

• flatMap, map
• flow
• foreach, zip, firstCompletedOf, fold,
    reduce, sequence, traverse
•   andThen, fallbackTo, onComplete,
    onFailure, onSuccess, recover
Composable Futures Rock

• Twitter uses composable (Twitter) futures, no
    actors
•   KloutAPI uses Play Framework
    AsyncResults, fed by Akka futures. Load
    dropped in half
ExecutorBenchmark
Statistical Nature




  Large standard deviation; values are not tightly clustered around the
     median; results vary a lot each time a measurement is taken.




Small standard deviation; values are tightly clustered around the median;
      results do not vary much each time a measurement is taken.
Standard Deviation

• Measurements tend to lie within one standard
 deviations either side of the mean
Configure Thread Pools at Deployment


• Number and type of processors and other
    hardware affects behavior
•   Interaction with other thread pools
•   Akka supports configuration files and
    configuration strings for setting up thread
    pools
Demo Time!

• Simple futures
• Try / catch / finally constructs
• flatMap
flatMap Demo

• Combination of Future.map() and
    List.flatten()
•   Walks through a list and generates a second
    list by flattening each item in the first list
•   Will not evaluate the passed-in functor if the
    future failed
•   This demo implements the pseudo-code that
    Marius Eriksen of Twitter showed for
    flatMap last week at the Bay Area Scala
    Enthusiasts meetup
flatMap Demo

1.Look up a token; return the user ID if
   successful, otherwise fail.
2. Use the user ID to obtain a user information
   if step 1 did not fail.
Code Summary

val userF: Future[User] =
    Future(authenticate(token))
      flatMap(id => getUser(id))
userF onComplete {
  case Right(value: User) =>
    println(value)
  case Left(exception) =>
    println(exception.getMessage)
}
Thank you!


            Mike Slinn
         slinnbooks.com

More Related Content

What's hot

Display earthquakes with Akka-http
Display earthquakes with Akka-httpDisplay earthquakes with Akka-http
Display earthquakes with Akka-httpPierangelo Cecchetto
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersSolix JJ
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsShashank L
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016takezoe
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
I18nize Scala programs à la gettext
I18nize Scala programs à la gettextI18nize Scala programs à la gettext
I18nize Scala programs à la gettextNgoc Dao
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarGal Marder
 
What’s expected in Spring 5
What’s expected in Spring 5What’s expected in Spring 5
What’s expected in Spring 5Gal Marder
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumNgoc Dao
 
Using Apache Camel as AKKA
Using Apache Camel as AKKAUsing Apache Camel as AKKA
Using Apache Camel as AKKAJohan Edstrom
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryTomer Gabel
 
No Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueNo Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueAndrus Adamchik
 
A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVMAlex Birch
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS DebuggingRami Sayar
 
Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011Raymond Roestenburg
 
Java 8 in Anger (JavaOne)
Java 8 in Anger (JavaOne)Java 8 in Anger (JavaOne)
Java 8 in Anger (JavaOne)Trisha Gee
 
Search and analyze your data with elasticsearch
Search and analyze your data with elasticsearchSearch and analyze your data with elasticsearch
Search and analyze your data with elasticsearchAnton Udovychenko
 
Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPdatamantra
 
Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1datamantra
 

What's hot (20)

Display earthquakes with Akka-http
Display earthquakes with Akka-httpDisplay earthquakes with Akka-http
Display earthquakes with Akka-http
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
I18nize Scala programs à la gettext
I18nize Scala programs à la gettextI18nize Scala programs à la gettext
I18nize Scala programs à la gettext
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
What’s expected in Spring 5
What’s expected in Spring 5What’s expected in Spring 5
What’s expected in Spring 5
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
 
Using Apache Camel as AKKA
Using Apache Camel as AKKAUsing Apache Camel as AKKA
Using Apache Camel as AKKA
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala Story
 
No Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueNo Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with Bootique
 
A tour of Java and the JVM
A tour of Java and the JVMA tour of Java and the JVM
A tour of Java and the JVM
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS Debugging
 
Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011
 
Java 8 in Anger (JavaOne)
Java 8 in Anger (JavaOne)Java 8 in Anger (JavaOne)
Java 8 in Anger (JavaOne)
 
Search and analyze your data with elasticsearch
Search and analyze your data with elasticsearchSearch and analyze your data with elasticsearch
Search and analyze your data with elasticsearch
 
Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
 
Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1
 

Viewers also liked

Super scaling singleton inserts
Super scaling singleton insertsSuper scaling singleton inserts
Super scaling singleton insertsChris Adkin
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingEmery Berger
 
Share and analyze geonomic data at scale by Andy Petrella and Xavier Tordoir
Share and analyze geonomic data at scale by Andy Petrella and Xavier TordoirShare and analyze geonomic data at scale by Andy Petrella and Xavier Tordoir
Share and analyze geonomic data at scale by Andy Petrella and Xavier TordoirSpark Summit
 
Information in a Current Condition
Information in a Current Condition Information in a Current Condition
Information in a Current Condition Emma Dickens
 
RTBI_Impact report_Final_PDF file
RTBI_Impact report_Final_PDF fileRTBI_Impact report_Final_PDF file
RTBI_Impact report_Final_PDF fileParasuram K
 
Help u india online education portal. find colleges, institutes in india
Help u india  online education portal. find colleges, institutes in indiaHelp u india  online education portal. find colleges, institutes in india
Help u india online education portal. find colleges, institutes in indiaHelp u india
 
Dynamic composition of virtual network functions in a cloud environment
Dynamic composition of virtual network functions in a cloud environmentDynamic composition of virtual network functions in a cloud environment
Dynamic composition of virtual network functions in a cloud environmentFrancesco Foresta
 
XML Amsterdam 2012 Keynote
XML Amsterdam 2012 KeynoteXML Amsterdam 2012 Keynote
XML Amsterdam 2012 Keynotejimfuller2009
 
Scala: the unpredicted lingua franca for data science
Scala: the unpredicted lingua franca  for data scienceScala: the unpredicted lingua franca  for data science
Scala: the unpredicted lingua franca for data scienceAndy Petrella
 
Reactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachReactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachRoland Kuhn
 
Groovy on Android (as of 2016)
Groovy on Android (as of 2016)Groovy on Android (as of 2016)
Groovy on Android (as of 2016)Kevin H.A. Tan
 
Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Knoldus Inc.
 
Introduction to Apache Kafka- Part 1
Introduction to Apache Kafka- Part 1Introduction to Apache Kafka- Part 1
Introduction to Apache Kafka- Part 1Knoldus Inc.
 
A dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioA dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioGioia Ballin
 

Viewers also liked (19)

Hanuman
HanumanHanuman
Hanuman
 
Super scaling singleton inserts
Super scaling singleton insertsSuper scaling singleton inserts
Super scaling singleton inserts
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic Multithreading
 
Share and analyze geonomic data at scale by Andy Petrella and Xavier Tordoir
Share and analyze geonomic data at scale by Andy Petrella and Xavier TordoirShare and analyze geonomic data at scale by Andy Petrella and Xavier Tordoir
Share and analyze geonomic data at scale by Andy Petrella and Xavier Tordoir
 
Information in a Current Condition
Information in a Current Condition Information in a Current Condition
Information in a Current Condition
 
RTBI_Impact report_Final_PDF file
RTBI_Impact report_Final_PDF fileRTBI_Impact report_Final_PDF file
RTBI_Impact report_Final_PDF file
 
Help u india online education portal. find colleges, institutes in india
Help u india  online education portal. find colleges, institutes in indiaHelp u india  online education portal. find colleges, institutes in india
Help u india online education portal. find colleges, institutes in india
 
Certificate_1
Certificate_1Certificate_1
Certificate_1
 
Dynamic composition of virtual network functions in a cloud environment
Dynamic composition of virtual network functions in a cloud environmentDynamic composition of virtual network functions in a cloud environment
Dynamic composition of virtual network functions in a cloud environment
 
Engineering Degree
Engineering DegreeEngineering Degree
Engineering Degree
 
XML Amsterdam 2012 Keynote
XML Amsterdam 2012 KeynoteXML Amsterdam 2012 Keynote
XML Amsterdam 2012 Keynote
 
Scala: the unpredicted lingua franca for data science
Scala: the unpredicted lingua franca  for data scienceScala: the unpredicted lingua franca  for data science
Scala: the unpredicted lingua franca for data science
 
Reactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachReactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the Beach
 
Groovy on Android (as of 2016)
Groovy on Android (as of 2016)Groovy on Android (as of 2016)
Groovy on Android (as of 2016)
 
Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2
 
Introduction to Apache Kafka- Part 1
Introduction to Apache Kafka- Part 1Introduction to Apache Kafka- Part 1
Introduction to Apache Kafka- Part 1
 
A dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioA dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenario
 
Scala at Netflix
Scala at NetflixScala at Netflix
Scala at Netflix
 
Maria
MariaMaria
Maria
 

Similar to Composable Futures with Akka 2.0

Agile Lab_BigData_Meetup_AKKA
Agile Lab_BigData_Meetup_AKKAAgile Lab_BigData_Meetup_AKKA
Agile Lab_BigData_Meetup_AKKAPaolo Platter
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...
Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...
Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...Flink Forward
 
Kafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life Example
Kafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life ExampleKafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life Example
Kafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life Exampleconfluent
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Martijn Verburg
 
Indic threads pune12-typesafe stack software development on the jvm
Indic threads pune12-typesafe stack software development on the jvmIndic threads pune12-typesafe stack software development on the jvm
Indic threads pune12-typesafe stack software development on the jvmIndicThreads
 
New hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfNew hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfKrystian Zybała
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersNLJUG
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Martijn Verburg
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
Building large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor frameworkBuilding large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor frameworkVignesh Sukumar
 
Spark Overview and Performance Issues
Spark Overview and Performance IssuesSpark Overview and Performance Issues
Spark Overview and Performance IssuesAntonios Katsarakis
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9Gal Marder
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with EpsilonSina Madani
 
Lessons Learned: Using Spark and Microservices
Lessons Learned: Using Spark and MicroservicesLessons Learned: Using Spark and Microservices
Lessons Learned: Using Spark and MicroservicesAlexis Seigneurin
 

Similar to Composable Futures with Akka 2.0 (20)

Agile Lab_BigData_Meetup_AKKA
Agile Lab_BigData_Meetup_AKKAAgile Lab_BigData_Meetup_AKKA
Agile Lab_BigData_Meetup_AKKA
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...
Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...
Flink Forward San Francisco 2019: Moving from Lambda and Kappa Architectures ...
 
Kafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life Example
Kafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life ExampleKafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life Example
Kafka Summit NYC 2017 Introduction to Kafka Streams with a Real-life Example
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
 
Indic threads pune12-typesafe stack software development on the jvm
Indic threads pune12-typesafe stack software development on the jvmIndic threads pune12-typesafe stack software development on the jvm
Indic threads pune12-typesafe stack software development on the jvm
 
New hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfNew hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdf
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
gcdtmp
gcdtmpgcdtmp
gcdtmp
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Building large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor frameworkBuilding large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor framework
 
Spark Overview and Performance Issues
Spark Overview and Performance IssuesSpark Overview and Performance Issues
Spark Overview and Performance Issues
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with Epsilon
 
Lessons Learned: Using Spark and Microservices
Lessons Learned: Using Spark and MicroservicesLessons Learned: Using Spark and Microservices
Lessons Learned: Using Spark and Microservices
 
Spark on YARN
Spark on YARNSpark on YARN
Spark on YARN
 

More from Mike Slinn

Evaluating Blockchain Companies
Evaluating Blockchain CompaniesEvaluating Blockchain Companies
Evaluating Blockchain CompaniesMike Slinn
 
Fullsize Smart Contracts That Learn
Fullsize Smart Contracts That Learn Fullsize Smart Contracts That Learn
Fullsize Smart Contracts That Learn Mike Slinn
 
Dotty (Scala 3) Preview
Dotty (Scala 3) PreviewDotty (Scala 3) Preview
Dotty (Scala 3) PreviewMike Slinn
 
EmpathyWorks – Towards an Event-Based Simulation/ML Hybrid Platform
EmpathyWorks – Towards an Event-Based Simulation/ML Hybrid PlatformEmpathyWorks – Towards an Event-Based Simulation/ML Hybrid Platform
EmpathyWorks – Towards an Event-Based Simulation/ML Hybrid PlatformMike Slinn
 
Smart Contracts That Learn
Smart Contracts That LearnSmart Contracts That Learn
Smart Contracts That LearnMike Slinn
 
Polyglot Ethereum - Smart Contracts for the Enterprise
Polyglot Ethereum - Smart Contracts for the EnterprisePolyglot Ethereum - Smart Contracts for the Enterprise
Polyglot Ethereum - Smart Contracts for the EnterpriseMike Slinn
 
Play Architecture, Implementation, Shiny Objects, and a Proposal
Play Architecture, Implementation, Shiny Objects, and a ProposalPlay Architecture, Implementation, Shiny Objects, and a Proposal
Play Architecture, Implementation, Shiny Objects, and a ProposalMike Slinn
 
Adobe Flash Platform for the Enterprise
Adobe Flash Platform for the EnterpriseAdobe Flash Platform for the Enterprise
Adobe Flash Platform for the EnterpriseMike Slinn
 

More from Mike Slinn (8)

Evaluating Blockchain Companies
Evaluating Blockchain CompaniesEvaluating Blockchain Companies
Evaluating Blockchain Companies
 
Fullsize Smart Contracts That Learn
Fullsize Smart Contracts That Learn Fullsize Smart Contracts That Learn
Fullsize Smart Contracts That Learn
 
Dotty (Scala 3) Preview
Dotty (Scala 3) PreviewDotty (Scala 3) Preview
Dotty (Scala 3) Preview
 
EmpathyWorks – Towards an Event-Based Simulation/ML Hybrid Platform
EmpathyWorks – Towards an Event-Based Simulation/ML Hybrid PlatformEmpathyWorks – Towards an Event-Based Simulation/ML Hybrid Platform
EmpathyWorks – Towards an Event-Based Simulation/ML Hybrid Platform
 
Smart Contracts That Learn
Smart Contracts That LearnSmart Contracts That Learn
Smart Contracts That Learn
 
Polyglot Ethereum - Smart Contracts for the Enterprise
Polyglot Ethereum - Smart Contracts for the EnterprisePolyglot Ethereum - Smart Contracts for the Enterprise
Polyglot Ethereum - Smart Contracts for the Enterprise
 
Play Architecture, Implementation, Shiny Objects, and a Proposal
Play Architecture, Implementation, Shiny Objects, and a ProposalPlay Architecture, Implementation, Shiny Objects, and a Proposal
Play Architecture, Implementation, Shiny Objects, and a Proposal
 
Adobe Flash Platform for the Enterprise
Adobe Flash Platform for the EnterpriseAdobe Flash Platform for the Enterprise
Adobe Flash Platform for the Enterprise
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 

Composable Futures with Akka 2.0

  • 1. Composable Futures with Akka 2.0 by Mike Slinn #akkafuture at Googleplex April 18, 2012
  • 2. Outline • Concurrency 101 • Akka concurrency options • Foundation: java.util.concurrent • Definitions • Functional programming and concurrency • Performance tuning • 3 demos
  • 4. About Mike Slinn • Principal at Micronautics Research • Hands-on architect, mentor, trainer • Interim technical leader for companies in transition • Recognized in US Federal court as a software expert • Author of Composable Futures with Akka 2.0 • Interested in artificial personality • Coordinator of BASE and Scala for Startups
  • 5. Horizontal Scale – More Cores
  • 6. Threads • Independent, heap-sharing execution contexts • Scheduled by the operating system • Creation is expensive in Java • Pools create additional complexity • Cache coherency issues
  • 8. Standard Thread Pools • Cached • Fixed • Scheduled • Single • Single scheduled • Fork / join (JDK 7 and improved jsr166y) • Variants with/without daemon threads often required
  • 9. Concurrency Definitions • Concurrent tasks are stateful, often with complex interactions • Parallelizable tasks are stateless, do not interact, and are composable
  • 10. java.util.concurrent • Akka is built on top of java.util.concurrent (j.u.c.) • Futures are designed to be used with a Callable, which returns a result • Executors contain factories and utility methods for concurrent classes • ExecutorService.shutdown()
  • 11. j.u.c. Primitives • Callable, Runnable • Threads, thread pools and Executors • CompletionService, CountDownLatch, concurrent collections, CyclicBarrier, Phaser, Semaphone, TimeUnit • Primitive Future<T>
  • 12. j.u.c. Is Too Hard To Use • Multithreaded programs tend to be buggy o Non-determinism caused by concurrent threads accessing (shared) mutable state. • Actors and transactions manage state and are therefore not the first solution you should consider. • To get deterministic processing, avoid (shared) mutable state.
  • 13. Concurrency Hazards • CPU registers • L1, L2 and L3 caches o L1 cache for each core o L2 cache shared by pairs of cores o L3 cache shared by all cores • Processors are different, so a program may run fine on one system but fail on another
  • 14. Cache Line Ping-Pong Result Array (Scala) var data = Array(threadCount)
  • 15. Cache Line Ping-Pong • 8.5 ms vs. 830 ms (C# code) • Multicore efficiency: 10%
  • 16. MESI Protocol • Each processor cache can be in one of four states: o Modified o Exclusive o Shared o Invalid • When one core writes to main memory, the entire cache block is marked invalid • Block sizes depend on processor (64 bytes, 128 bytes, etc.)
  • 17. Cache Line Ping-Pong • Manifests even when external state is not shared o One or more cores repeatedly invalidate caches of the other cores, even while accessing isolated state. o The other cores must read data from main memory instead of their local cache o Slows program up to two orders of magnitude.
  • 18. Cache Line Ping-Pong 1.j.u.c. solution: @volatile var data = Array(threadCount) synchronized(data) { data(i) = whatever } 2.Do not access external mutable state from a thread 3. Use functional programming techniques
  • 19. Large, Realtime Guidelines by Prismatic • Use functional programming to build fine- grained, flexible abstractions. • Compose these abstractions to express problem-specific logic. • Prefer lightweight, composable custom abstractions rather than monolithic frameworks (e.g., Hadoop).
  • 20. Functional-Style Pipelines • *nix pipes (linear) • Scala parallel collections & Akka composable futures (parallel)
  • 21. Better Concurrency Options • Ordered by increasing complexity & overhead o j.u.c. o Scala parallel collections o Akka futures* (Java & Scala) o Akka/Scala dataflow* o Akka actors (Java & Scala) • You can mix & match the above * Covered in my book: “Composable Futures with Akka 2.0”  Covered in my April 23 InfoQ article.
  • 22. Scala Parallel Collections • Very easy to use • Not configurable • Block • Composable • Easy to reason with • Benefits from ongoing improvements to ForkJoinPool o (Scala uses jsr166y)
  • 25. Akka/Scala Dataflow* • Callable from Scala only • Has peculiar operators • Easy to reason with • Designed for shared mutable state • Dataflow blocks are composable • Good for coordination of asynchronous activities • Good for consolidating multiple sources of data
  • 26. Akka Actors • Callable from Java & Scala • Over-hyped (remember EJB 2?) • Most complex option • Distributed concurrency: can scale beyond one motherboard • Not composable • Can be difficult or impossible to prove correct • This should be your last option to consider
  • 27. Akka Futures • Callable from Java & Scala • More flexible than Scala parallel collections • Much less complex than Akka actors • Composable • Easy to reason with • Payloads (Callables) should not have side effects • Should not be used with shared mutable state
  • 28. What is a Future? • Holder for a result that will become available at a later time. • Each future is backed by a thread. • If the computation fails, the future can also hold the resulting Throwable. • Write-once (immutable) • Akka and Twitter futures are composable and transformable (j.u.c. futures are not)
  • 29. Akka & Twitter Futures • Manage concurrency • Higher-level than j.u.c. primitives • Immutable • Inexpensive • Can be preset to a value or exception when created. • Blocking and non-blocking operations supported
  • 30. Composable Futures • Operations on a future or a collection of futures can be chained together without blocking • Transformations such as map and flatMap can be applied to a single future • Collections of futures can be manipulated
  • 31. Akka Future Operations • flatMap, map • flow • foreach, zip, firstCompletedOf, fold, reduce, sequence, traverse • andThen, fallbackTo, onComplete, onFailure, onSuccess, recover
  • 32. Composable Futures Rock • Twitter uses composable (Twitter) futures, no actors • KloutAPI uses Play Framework AsyncResults, fed by Akka futures. Load dropped in half
  • 34. Statistical Nature Large standard deviation; values are not tightly clustered around the median; results vary a lot each time a measurement is taken. Small standard deviation; values are tightly clustered around the median; results do not vary much each time a measurement is taken.
  • 35. Standard Deviation • Measurements tend to lie within one standard deviations either side of the mean
  • 36. Configure Thread Pools at Deployment • Number and type of processors and other hardware affects behavior • Interaction with other thread pools • Akka supports configuration files and configuration strings for setting up thread pools
  • 37. Demo Time! • Simple futures • Try / catch / finally constructs • flatMap
  • 38. flatMap Demo • Combination of Future.map() and List.flatten() • Walks through a list and generates a second list by flattening each item in the first list • Will not evaluate the passed-in functor if the future failed • This demo implements the pseudo-code that Marius Eriksen of Twitter showed for flatMap last week at the Bay Area Scala Enthusiasts meetup
  • 39. flatMap Demo 1.Look up a token; return the user ID if successful, otherwise fail. 2. Use the user ID to obtain a user information if step 1 did not fail.
  • 40. Code Summary val userF: Future[User] = Future(authenticate(token)) flatMap(id => getUser(id)) userF onComplete { case Right(value: User) => println(value) case Left(exception) => println(exception.getMessage) }
  • 41. Thank you! Mike Slinn slinnbooks.com

Editor's Notes

  1. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.htmlhttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html
  2. http://simplygenius.net/Article/FalseSharinghttp://en.wikipedia.org/wiki/MESI_protocolAMD Opteron and Intel i7 caches are quite different, for example
  3. Scala futures?