SlideShare una empresa de Scribd logo
1 de 58
Concurrency Constructs
      overview
      Let’s jump into
Who is there
Stas Shevchenko
Accenture

Based on
Survey of Concurrency Constructs
Ted Leung
Sun Microsystems
Mainstream is 10 years in the past
Something happened in




     2002
Fraction of Chip reachable
    in one clock cycle
Converting to Figure




[Source:] A Wire-Delay Scalable Microprocessor Architecture for High Performance
Systems
Processor Clock Speed
Growing CPU performance
Programming style impact on
       performance


         Sequences



       Multithreading
Mobile (up to 4)
1 Mainstream (4)
Office (12)
SUN Unit (up to 128)
Ignoring cores…
2 cores won't hurt you

4 cores will hurt a little

8 cores will hurt a bit

16 will start hurting

32 cores will hurt a lot (2009)

...

1 M cores ouch (2019)
Java is so Java
Java Memory Model
wait - notify
Thread.yield()
Thread.sleep()

synchronized

Executor Framework -> NIO (2)
Books
Books
We DO
• Threads
  – Program counter
  – Own stack
  – Shared Memory
• Locks
Shared memory
Unpredictable state
Crash in critical region
Issues
• Locks
  – manually lock and unlock
  – lock ordering is a big problem
  – locks are not compositional
• How do we decide what is concurrent?
• Need to pre-design, but now we have to
  retrofit concurrency via new requirements
Design Goals/Space
Mutual Exclusion
Serialization / Ordering
Inherent / Implicit vs Explicit
Fine / Medium / Coarse grained
Composability
A good solution
• Substantially less error prone
• Makes it much easier to identify concurrency
• Runs on today’s (and future) parallel hardware
  – Works if you keep adding cores/threads
Theory
Functional Programming
Actors
CSP
CCS
petri-nets
pi-calculus
join-calculus
The models
• Transactional Memory
  – Persistent data structures
• Actors
• Dataflow
• Tuple spaces
Transactional memory
analogous to database transactions
Hardware vs. software implementations
Idea goes as far back as 1986
First appearance in a programming language:
Concurrent Haskell 2005
Example Clojure
(defn deposit [account amount]
  (dosync
     (let [owner (account :owner)
            balance-ref (account :balance-ref)]
        (do
            (alter balance-ref + amount)
            (println “depositing” amount
                     (account :owner)))))))
STM Design Space
STM Algorithms / Strategies
  Granularity
      word vs block
Locks vs Optimistic concurrency
Conflict detection
  eager vs lazy
Contention management
STM Problems
• Non abortable operations
  – I/O
• STM Overhead
  – read/write barrier elimination
• Where to place transaction boundaries?
• Still need condition variables
  – ordering problems are important
Implementations
Clojure STM - via Refs
Akka/Scala
   copy from Clojure
Haskell/GHC
   Use logs and aborts txns
Persistent Data Structures
In Clojure, combined with STM
Motivated by copy on write
hash-map, vector, sorted map
Available Data Structures
Lists, Vectors, Maps
hash list based on Vlists
VDList - deques based on Vlists
red-black trees
Real Time Queues and Deques
deques, output-restricted deques
binary random access lists
binomial heaps
skew binary random access lists
skew binomial heaps
catenable lists
heaps with efficient merging
catenable deques
Problem
• Not really a full model
• Oriented towards functional programming
Actors
Invented by Carl Hewitt at MIT (1973)
Formal Model
   Programming languages
   Hardware
   Led to continuations, Scheme
Recently revived by Erlang
   Erlang’s model is not derived explicitly from
Actors
Simple
Example
object account extends Actor
{
     private var balance = 0

     def act() {
          loop {
                 react {
                       case Withdraw(amount) =>
                            balance -= amount
                            sender ! Balance(balance)
                       case Deposit(amount) =>
                            balance += amount
                            sender ! Balance(balance)
                       case BalanceRequest =>
                            sender ! Balance(balance)
                       case TerminateRequest =>
          }
     }
}
Problems
DOS of the actor mail queue
Multiple actor coordination
   reinvent transactions?
Actors can still deadlock and starve
Programmer defines granularity
   by choosing what is an actor
Impelmentations
Scala
   Akka Actors
   Scala Actors
   Lift Actors
Erlang
   OTP
CLR
   F# / Axum
Perfomance
Actor create/destroy
Message passing
Memory usage
Erlang vs JVM
Erlang
   per process GC heap
   tail call
   distributed
JVM
   per JVM heap
   tail call (fixed in JSR-292?, at least in scalac)
   not distributed
   few kinds of actors (Scala)
Actor Variants
Clojure Agents
   Designed for loosely coupled stuff
   Code/actions sent to agents
   Code is queued when it hits the agent
   Agent framework guarantees serialization
   State of agent is always available for read (unlike
actors which could be busy processing when you send a
read message)
   not in favor of transparent distribution
   Clojure agents can operate in an ‘open world’ - actors
answer a specific set of messages
Dataflow
Dataflow is a software architecture based on the idea
that changing the value of a variable should automatically
force recalculation of the values of variables which
depend on its value
Bill Ackerman’s PhD Thesis at MIT (1984)
Declarative Concurrency in functional languages
Research in the 1980’s and 90’s
Inherent concurrency
    Turns out to be very difficult to implement
Interest in declarative concurrency is slowly returning
The Model
Dataflow Variables
   create variable
   bind value
   read value or block
Threads
Dataflow Streams
   List whose tail is an unbound dataflow variable
Deterministic computation!
Example: Variables 1
object Test5 extends App {
 val x, y, z = new DataFlowVariable[Int]

    val main = thread {
     x << 1

        if (x() > y()) { z << x } else {z << y }
    }

    val setY = thread {
      Thread.sleep(5000)
      y << 2
    }

    main ! 'exit
    setY ! 'exit
}
Example: Streams (Oz)
fun {Ints N Max}
      if N == Max then nil
      else
            {Delay 1000}
            N|{Ints N+1 Max}
      end
end
fun {Sum S Stream}
      case Stream of nil then S
      [] H|T then S|{Sum H+S T} end
end
local X Y in
      thread X = {Ints 0 1000} end
      thread Y = {Sum 0 X} end
      {Browse Y}
end
Implementations
Mozart Oz
  http://www.mozart-oz.org/
Akka
  http://github.com/jboner/scala-dataflow
  dataflow variables and streams
Ruby library
  http://github.com/larrytheliquid/dataflow
  dataflow variables and streams
Groovy
  http://code.google.com/p/gparallelizer/
Problems
Can’t handle non-determinism
  like a server
  Need ports
      this leads to actor like things
Tuple Spaces Model
Originated in Linda (1984)
Popularized by Jini
The Model
Three operations
  write() (out)
  take() (in)
  read()
The Model
Space uncoupling
Time uncoupling
Readers are decoupled from Writers
Content addressable by pattern matching
Can emulate
   Actor like continuations
   CSP
   Message Passing
   Semaphores
Example
public class Account implements Entry {
     public Integer accountNo;
     public Integer value;
     public Account() { ... }
     public Account(int accountNo, int value {
          this.accountNo = newInteger(accountNo);
          this.value = newInteger(value);
     }
}

try {
        Account newAccount = new Account(accountNo, value);
        space.write(newAccount, null, Lease.FOREVER);
}

space.read(accountNo);
Implementations
Jini/JavaSpaces
   http://incubator.apache.org/river/RIVER/inde
x.html
BlitzSpaces
   http://www.dancres.org/blitz/blitz_js.html
PyLinda
   http://code.google.com/p/pylinda/
Rinda
   built in to Ruby
Problems
Low level
High latency to the space - the space is
contention point / hot spot
Scalability
More for distribution than concurrency
Projects
Scala
Erlang
Clojure
Kamaelia
Haskell
Axum/F#
Mozart/Oz
Akka
Work to be done
More in depth comparisons on 4+ core
platforms
Higher level frameworks
Application architectures/patterns
   Web
   Middleware
Outcomes
F..ck the shared state,
Mutable means non-scalable

It is not too early!
QA

Más contenido relacionado

La actualidad más candente

Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuHavoc Pennington
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and FallaciesRoman Elizarov
 
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
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
Writing DSL's in Scala
Writing DSL's in ScalaWriting DSL's in Scala
Writing DSL's in ScalaAbhijit Sharma
 
Using Scala for building DSLs
Using Scala for building DSLsUsing Scala for building DSLs
Using Scala for building DSLsIndicThreads
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)mircodotta
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介scalaconfjp
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaSaleem Ansari
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slidesMartin Odersky
 

La actualidad más candente (19)

Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
Scala profiling
Scala profilingScala profiling
Scala profiling
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and Fallacies
 
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
 
Devoxx
DevoxxDevoxx
Devoxx
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Writing DSL's in Scala
Writing DSL's in ScalaWriting DSL's in Scala
Writing DSL's in Scala
 
Using Scala for building DSLs
Using Scala for building DSLsUsing Scala for building DSLs
Using Scala for building DSLs
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
 

Destacado

Diari del 2 de desembre de 2014
Diari del 2 de desembre de 2014Diari del 2 de desembre de 2014
Diari del 2 de desembre de 2014diarimes
 
10 Gründe für die Cloud
10 Gründe für die Cloud10 Gründe für die Cloud
10 Gründe für die CloudJuliane Waack
 
Biology Flash Cards 5
Biology Flash Cards 5Biology Flash Cards 5
Biology Flash Cards 5guestabc190
 
Larevue de presse de la semaine du 12 au 18 octobre 2015
Larevue de presse de la semaine du 12 au 18 octobre 2015Larevue de presse de la semaine du 12 au 18 octobre 2015
Larevue de presse de la semaine du 12 au 18 octobre 2015KYLIA France
 
Serrano amparo presentació _competic2
Serrano amparo presentació _competic2Serrano amparo presentació _competic2
Serrano amparo presentació _competic2competic
 
Manual siemens accesorio calienta platos hw290562
Manual siemens   accesorio calienta platos hw290562Manual siemens   accesorio calienta platos hw290562
Manual siemens accesorio calienta platos hw290562Alsako Electrodomésticos
 
Treinamento ASP.NET
Treinamento ASP.NETTreinamento ASP.NET
Treinamento ASP.NETIgor Musardo
 
plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...
plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...
plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...Diana Morales Irato
 
EBE12-Tweets european-ecommerce-conferece-12-eec12
EBE12-Tweets european-ecommerce-conferece-12-eec12EBE12-Tweets european-ecommerce-conferece-12-eec12
EBE12-Tweets european-ecommerce-conferece-12-eec12Rosa Bermejo
 
Präsentation zum 13. IfK-Praxisforum
Präsentation zum 13. IfK-Praxisforum Präsentation zum 13. IfK-Praxisforum
Präsentation zum 13. IfK-Praxisforum Jakob Ohme
 
BUENAS PRECTICAS GANADERAS
BUENAS PRECTICAS GANADERASBUENAS PRECTICAS GANADERAS
BUENAS PRECTICAS GANADERAS3125034802
 
Marketing Analytics 101: How to Measure the Effectiveness of Your Website
Marketing Analytics 101: How to Measure the Effectiveness of Your WebsiteMarketing Analytics 101: How to Measure the Effectiveness of Your Website
Marketing Analytics 101: How to Measure the Effectiveness of Your WebsiteHubSpot
 

Destacado (20)

Diari del 2 de desembre de 2014
Diari del 2 de desembre de 2014Diari del 2 de desembre de 2014
Diari del 2 de desembre de 2014
 
Social Media Delphi 2012 - Ergebnisbericht komplett
Social Media Delphi 2012 - Ergebnisbericht komplettSocial Media Delphi 2012 - Ergebnisbericht komplett
Social Media Delphi 2012 - Ergebnisbericht komplett
 
10 Gründe für die Cloud
10 Gründe für die Cloud10 Gründe für die Cloud
10 Gründe für die Cloud
 
Dossier laboratorio CTAP
Dossier laboratorio CTAPDossier laboratorio CTAP
Dossier laboratorio CTAP
 
Eada View 14
Eada View 14Eada View 14
Eada View 14
 
Biology Flash Cards 5
Biology Flash Cards 5Biology Flash Cards 5
Biology Flash Cards 5
 
Larevue de presse de la semaine du 12 au 18 octobre 2015
Larevue de presse de la semaine du 12 au 18 octobre 2015Larevue de presse de la semaine du 12 au 18 octobre 2015
Larevue de presse de la semaine du 12 au 18 octobre 2015
 
Huzefa CycleWala_Resume
Huzefa CycleWala_ResumeHuzefa CycleWala_Resume
Huzefa CycleWala_Resume
 
Wissensarbeit20 131101
Wissensarbeit20 131101Wissensarbeit20 131101
Wissensarbeit20 131101
 
Serrano amparo presentació _competic2
Serrano amparo presentació _competic2Serrano amparo presentació _competic2
Serrano amparo presentació _competic2
 
Can ufo doc_10
Can ufo doc_10Can ufo doc_10
Can ufo doc_10
 
Manual siemens accesorio calienta platos hw290562
Manual siemens   accesorio calienta platos hw290562Manual siemens   accesorio calienta platos hw290562
Manual siemens accesorio calienta platos hw290562
 
Comunicação e sustentabilidade
Comunicação e sustentabilidadeComunicação e sustentabilidade
Comunicação e sustentabilidade
 
Treinamento ASP.NET
Treinamento ASP.NETTreinamento ASP.NET
Treinamento ASP.NET
 
plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...
plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...
plancc_escenarios_de_mitigacion_del_cambio_climatico_en_el_peru_al_2050._anal...
 
EBE12-Tweets european-ecommerce-conferece-12-eec12
EBE12-Tweets european-ecommerce-conferece-12-eec12EBE12-Tweets european-ecommerce-conferece-12-eec12
EBE12-Tweets european-ecommerce-conferece-12-eec12
 
Präsentation zum 13. IfK-Praxisforum
Präsentation zum 13. IfK-Praxisforum Präsentation zum 13. IfK-Praxisforum
Präsentation zum 13. IfK-Praxisforum
 
BUENAS PRECTICAS GANADERAS
BUENAS PRECTICAS GANADERASBUENAS PRECTICAS GANADERAS
BUENAS PRECTICAS GANADERAS
 
Welders qualification
Welders qualificationWelders qualification
Welders qualification
 
Marketing Analytics 101: How to Measure the Effectiveness of Your Website
Marketing Analytics 101: How to Measure the Effectiveness of Your WebsiteMarketing Analytics 101: How to Measure the Effectiveness of Your Website
Marketing Analytics 101: How to Measure the Effectiveness of Your Website
 

Similar a Concurrency Constructs Overview

A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency ConstructsTed Leung
 
Oscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleOscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleMartin Odersky
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futureTakayuki Muranushi
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustEvan Chan
 
Functional Programming and Composing Actors
Functional Programming and Composing ActorsFunctional Programming and Composing Actors
Functional Programming and Composing Actorslegendofklang
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 

Similar a Concurrency Constructs Overview (20)

A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency Constructs
 
Oscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleOscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simple
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
Functional Programming and Composing Actors
Functional Programming and Composing ActorsFunctional Programming and Composing Actors
Functional Programming and Composing Actors
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - 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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - 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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Concurrency Constructs Overview

  • 1. Concurrency Constructs overview Let’s jump into
  • 2. Who is there Stas Shevchenko Accenture Based on Survey of Concurrency Constructs Ted Leung Sun Microsystems
  • 3. Mainstream is 10 years in the past
  • 5. Fraction of Chip reachable in one clock cycle
  • 6. Converting to Figure [Source:] A Wire-Delay Scalable Microprocessor Architecture for High Performance Systems
  • 9. Programming style impact on performance Sequences Multithreading
  • 13. SUN Unit (up to 128)
  • 14. Ignoring cores… 2 cores won't hurt you 4 cores will hurt a little 8 cores will hurt a bit 16 will start hurting 32 cores will hurt a lot (2009) ... 1 M cores ouch (2019)
  • 15. Java is so Java Java Memory Model wait - notify Thread.yield() Thread.sleep() synchronized Executor Framework -> NIO (2)
  • 16. Books
  • 17. Books
  • 18. We DO • Threads – Program counter – Own stack – Shared Memory • Locks
  • 22. Issues • Locks – manually lock and unlock – lock ordering is a big problem – locks are not compositional • How do we decide what is concurrent? • Need to pre-design, but now we have to retrofit concurrency via new requirements
  • 23. Design Goals/Space Mutual Exclusion Serialization / Ordering Inherent / Implicit vs Explicit Fine / Medium / Coarse grained Composability
  • 24. A good solution • Substantially less error prone • Makes it much easier to identify concurrency • Runs on today’s (and future) parallel hardware – Works if you keep adding cores/threads
  • 26. The models • Transactional Memory – Persistent data structures • Actors • Dataflow • Tuple spaces
  • 27. Transactional memory analogous to database transactions Hardware vs. software implementations Idea goes as far back as 1986 First appearance in a programming language: Concurrent Haskell 2005
  • 28. Example Clojure (defn deposit [account amount] (dosync (let [owner (account :owner) balance-ref (account :balance-ref)] (do (alter balance-ref + amount) (println “depositing” amount (account :owner)))))))
  • 29. STM Design Space STM Algorithms / Strategies Granularity word vs block Locks vs Optimistic concurrency Conflict detection eager vs lazy Contention management
  • 30. STM Problems • Non abortable operations – I/O • STM Overhead – read/write barrier elimination • Where to place transaction boundaries? • Still need condition variables – ordering problems are important
  • 31. Implementations Clojure STM - via Refs Akka/Scala copy from Clojure Haskell/GHC Use logs and aborts txns
  • 32. Persistent Data Structures In Clojure, combined with STM Motivated by copy on write hash-map, vector, sorted map
  • 33. Available Data Structures Lists, Vectors, Maps hash list based on Vlists VDList - deques based on Vlists red-black trees Real Time Queues and Deques deques, output-restricted deques binary random access lists binomial heaps skew binary random access lists skew binomial heaps catenable lists heaps with efficient merging catenable deques
  • 34. Problem • Not really a full model • Oriented towards functional programming
  • 35. Actors Invented by Carl Hewitt at MIT (1973) Formal Model Programming languages Hardware Led to continuations, Scheme Recently revived by Erlang Erlang’s model is not derived explicitly from Actors
  • 37. Example object account extends Actor { private var balance = 0 def act() { loop { react { case Withdraw(amount) => balance -= amount sender ! Balance(balance) case Deposit(amount) => balance += amount sender ! Balance(balance) case BalanceRequest => sender ! Balance(balance) case TerminateRequest => } } }
  • 38. Problems DOS of the actor mail queue Multiple actor coordination reinvent transactions? Actors can still deadlock and starve Programmer defines granularity by choosing what is an actor
  • 39. Impelmentations Scala Akka Actors Scala Actors Lift Actors Erlang OTP CLR F# / Axum
  • 41. Erlang vs JVM Erlang per process GC heap tail call distributed JVM per JVM heap tail call (fixed in JSR-292?, at least in scalac) not distributed few kinds of actors (Scala)
  • 42. Actor Variants Clojure Agents Designed for loosely coupled stuff Code/actions sent to agents Code is queued when it hits the agent Agent framework guarantees serialization State of agent is always available for read (unlike actors which could be busy processing when you send a read message) not in favor of transparent distribution Clojure agents can operate in an ‘open world’ - actors answer a specific set of messages
  • 43. Dataflow Dataflow is a software architecture based on the idea that changing the value of a variable should automatically force recalculation of the values of variables which depend on its value Bill Ackerman’s PhD Thesis at MIT (1984) Declarative Concurrency in functional languages Research in the 1980’s and 90’s Inherent concurrency Turns out to be very difficult to implement Interest in declarative concurrency is slowly returning
  • 44. The Model Dataflow Variables create variable bind value read value or block Threads Dataflow Streams List whose tail is an unbound dataflow variable Deterministic computation!
  • 45. Example: Variables 1 object Test5 extends App { val x, y, z = new DataFlowVariable[Int] val main = thread { x << 1 if (x() > y()) { z << x } else {z << y } } val setY = thread { Thread.sleep(5000) y << 2 } main ! 'exit setY ! 'exit }
  • 46. Example: Streams (Oz) fun {Ints N Max} if N == Max then nil else {Delay 1000} N|{Ints N+1 Max} end end fun {Sum S Stream} case Stream of nil then S [] H|T then S|{Sum H+S T} end end local X Y in thread X = {Ints 0 1000} end thread Y = {Sum 0 X} end {Browse Y} end
  • 47. Implementations Mozart Oz http://www.mozart-oz.org/ Akka http://github.com/jboner/scala-dataflow dataflow variables and streams Ruby library http://github.com/larrytheliquid/dataflow dataflow variables and streams Groovy http://code.google.com/p/gparallelizer/
  • 48. Problems Can’t handle non-determinism like a server Need ports this leads to actor like things
  • 49. Tuple Spaces Model Originated in Linda (1984) Popularized by Jini
  • 50. The Model Three operations write() (out) take() (in) read()
  • 51. The Model Space uncoupling Time uncoupling Readers are decoupled from Writers Content addressable by pattern matching Can emulate Actor like continuations CSP Message Passing Semaphores
  • 52. Example public class Account implements Entry { public Integer accountNo; public Integer value; public Account() { ... } public Account(int accountNo, int value { this.accountNo = newInteger(accountNo); this.value = newInteger(value); } } try { Account newAccount = new Account(accountNo, value); space.write(newAccount, null, Lease.FOREVER); } space.read(accountNo);
  • 53. Implementations Jini/JavaSpaces http://incubator.apache.org/river/RIVER/inde x.html BlitzSpaces http://www.dancres.org/blitz/blitz_js.html PyLinda http://code.google.com/p/pylinda/ Rinda built in to Ruby
  • 54. Problems Low level High latency to the space - the space is contention point / hot spot Scalability More for distribution than concurrency
  • 56. Work to be done More in depth comparisons on 4+ core platforms Higher level frameworks Application architectures/patterns Web Middleware
  • 57. Outcomes F..ck the shared state, Mutable means non-scalable It is not too early!
  • 58. QA

Notas del editor

  1. and sometimes called the instruction address register (IAR)[1] or just part of the instruction sequencer,[2] is a processor register that indicates where a computer is in its programsequence.
  2. For the concept, see Mutually exclusive events.&quot;mutex&quot; redirects here. For the computer program object that negotiates mutual exclusion among threads, see lock (computer science).Coarse-grained systems consist of fewer, larger components than fine-grained systems; a coarse-grained description of a system regards large subcomponents while a fine-grained description regards smaller components of which the larger ones are composed.
  3. - the process calculi (or process algebras) are a diverse family of related approaches for formally modellingconcurrent systems.Communicating Sequential Processes (limbo and Go) - process calculusThe approach taken in developing CSP into a process algebra was influenced by Robin Milner&apos;s work on theCalculus of Communicating Systems (CCS), and vice versa. CCS is useful for evaluating the qualitative correctness of properties of a system such as deadlock or livelockA Petri net (also known as a place/transition net or P/T net) is one of several mathematical modeling languages for the description of distributed systemsPi - as a continuation of work on the process calculus CCS (Calculus of Communicating Systems). The π-calculus allows channel names to be communicated along the channels themselves, and in this way it is able to describe concurrent computations whose network configuration may change during the computation.The join-calculus is a member of the -calculus family of process calculi, and can be considered, at its core, an asynchronous -calculus with several strong restrictions[3]:Scope restriction, reception, and replicated reception are syntactically merged into a single construct, the definition;Communication occurs only on defined names;For every defined name there is exactly one replicated reception.
  4. Transactional memory attempts to simplify parallel programming by allowing a group of load and store instructions to execute in an atomic way. It is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing.A dataflow network is a network of concurrently executing processes or automata that can communicate by sending data over channels (seemessage passing.)A tuple space is an implementation of the associative memory paradigm for parallel/distributed computing. It provides a repository of tuples that can be accessed concurrently. As an illustrative example, consider that there are a group of processors that produce pieces of data and a group of processors that use the data. Producers post their data as tuples in the space, and the consumers then retrieve data from the space that match a certain pattern. This is also known as the blackboard metaphor. Tuple space may be thought as a form of distributed shared memory.Tuple spaces were the theoretical underpinning of the Linda language developed by David Gelernter and Nicholas Carriero at Yale University.Implementations of tuple spaces have also been developed for Java (JavaSpaces), Lisp, Lua, Prolog, Python, Ruby, Smalltalk, Tcl, and the.NET framework.
  5. . A contention management process is invoked when a conflict occurs between a first transaction and a second transaction. The pre-determined commit order is used in the contention management process to aid in determining whether the first transaction or the second transaction should win the conflict and be allowed to proceed.&quot;
  6. Dataflow concurrency is deterministic. This means that it will always behave the same. If you run it once and it yields output 5 then it will do that every time, run it 10 million times, same result. If it on the other hand deadlocks the first time you run it, then it will deadlock every single time you run it. Also, there is no difference between sequential code and concurrent code. These properties makes it very easy to reason about concurrency. The limitation is that the code needs to be side-effect free, e.g. deterministic. You can’t use exceptions, time, random etc., but need to treat the part of your program that uses dataflow concurrency as a pure function with input and output.The best way to learn how to program with dataflow variables is to read the fantastic book Concepts, Techniques, and Models of Computer Programming. By Peter Van Roy and Seif Haridi.